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

EntityManager – delete

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

Leave a Reply