Home

PrePersist

PrePersist is a lifecycle callback or event in some object-relational mapping frameworks, triggered just before a new entity is persisted (inserted) into the database. It is part of the set of lifecycle events that allow developers to execute custom logic at specific points in an entity’s lifecycle, without manually invoking code around every create operation.

In Java Persistence API (JPA), a method annotated with @PrePersist is invoked before the entity is inserted.

In Doctrine ORM (PHP) and similar frameworks, prePersist serves the same purpose: a method on the entity

Common uses of prePersist include initializing derived or required fields, setting default values that depend on

Notes: prePersist occurs only for new entities and not for updates. It can be complemented by related

The
callback
method
typically
takes
no
arguments
and
returns
void,
and
it
can
be
public,
protected,
or
package-private.
If
the
method
throws
a
runtime
exception,
the
persist
operation
can
be
aborted.
PrePersist
is
executed
only
for
new
entities
that
are
being
persisted
for
the
first
time,
and
not
for
entities
loaded
from
the
database.
can
be
designated
to
run
before
the
INSERT
statement
is
issued.
This
can
be
configured
via
annotations
or
mappings.
The
callback
is
commonly
used
to
initialize
fields,
set
default
values,
or
perform
automatic
timestamping
(for
example,
setting
a
createdAt
field)
prior
to
the
database
operation.
the
entity’s
current
state,
and
enforcing
invariants
before
the
entity
is
saved.
It
is
typically
paired
with
a
post-persist
callback
that
runs
after
the
record
has
been
created.
events
such
as
preUpdate,
postPersist,
and
postLoad
depending
on
the
framework.