Home > AI > Backend > SpringBoot > mysql-connector-java >

JPA Entity Lifecycle Events

JPA specifies seven optional lifecycle events that are called:

  • before persist is called for a new entity – @PrePersist
  • after persist is called for a new entity – @PostPersist
  • before an entity is removed – @PreRemove
  • after an entity has been deleted – @PostRemove
  • before the update operation – @PreUpdate
  • after an entity is updated – @PostUpdate
  • after an entity has been loaded – @PostLoad

Example

Bar.java

@Data
@NoArgsConstructor
@Entity
public class Bar {

    @Id
    @GeneratedValue
    public Long id;

    @Column(name = "operation")
    private String operation;

    @Column(name = "timestamp")
    private long timestamp;


    private String name;
    Bar(String name) {
        this.name = name;
    }


    @PrePersist
    public void onPrePersist() {
        audit("INSERT");
    }

    @PreUpdate
    public void onPreUpdate() {
        audit("UPDATE");
    }

    @PreRemove
    public void onPreRemove() {
        audit("DELETE");
    }

    private void audit(String operation) {
        setOperation(operation);
        setTimestamp((new Date()).getTime());
        System.out.println(this.toString());
    }

}

Demo11Application.java

@Slf4j
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class Demo11Application {


    public static EntityManagerFactory emf =
            Persistence.createEntityManagerFactory("PERSISTENCE1");




    public static void createBar() {
        log.info("[Shark] Create Bar");

        EntityManager em = emf.createEntityManager();


        em.getTransaction().begin();

        Bar bar = new Bar("braddon");
        em.persist(bar);


        em.getTransaction().commit();
        em.close();

        log.info("[Shark]" + bar.toString());
    }

    public static void updateBar() {
        log.info("[Shark] Update Bar");

        EntityManager em = emf.createEntityManager();

        Bar bar = (Bar) em.createQuery(
                        "SELECT e FROM Bar e WHERE e.name = :name")
                    .setParameter("name", "braddon")
                    .getResultList()
                    .get(0);
        bar.setName("dickson");
        em.getTransaction().begin();
        em.getTransaction().commit();
        em.close();

        log.info("[Shark]" + bar.toString());
    }


    public static void deleteBar() {
        log.info("[Shark] Delete Bar");

        EntityManager em = emf.createEntityManager();

        Bar bar = (Bar) em.createQuery(
                        "SELECT e FROM Bar e WHERE e.name = :name")
                .setParameter("name", "dickson")
                .getResultList()
                .get(0);
        em.getTransaction().begin();
        em.remove(bar);
        em.getTransaction().commit();
        em.close();

        log.info("[Shark]" + bar.toString());
    }


	public static void main(String[] args) {

        SpringApplication.run(Demo11Application.class, args);

        createBar();
        updateBar();
        deleteBar();

	}


}

resources/META-INF/persistence.xml

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="PERSISTENCE1">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>


        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="root" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
        </properties>

    </persistence-unit>

</persistence>

resources/application.properties



server.port = 8888


##################
# Mysql
##################
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.jpa.show-sql= false

Note

The database codes have to behind the SpringApplication

Leave a Reply