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

EntityManager – update

Example

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

Leave a Reply