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

EntityManager – create

Example 1:

@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());
    }

}
 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());
    }

Leave a Reply