Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

spring - JPA Callback not being called

I am new to hibernate. I want to know if any crud operation happens so I decided to use jpa callback annotations. The problem is any of those @PrePersist @PostPersist @PreRemove @PostRemove not being called when I run the project and use UI components to perform delete & add operations. I use primefaces datatable so delete operation bounded to a ManagedBean -> MessageService ->MessageDAO. IF I only execute the main file to test it it works perfectly

MessageDAO:

@Component
public class MessageDAO {


@PersistenceContext
private EntityManager em;

@Transactional
public void register(Message message) {
    em.persist(message);
}


@Transactional
public void delete(Integer id) {

     Message m =  em.find(Message.class, id);
     em.remove(em.merge(m));
   }
}

MessageListener

public class MessageListener {

@PrePersist
public void prePersist(Message o) {
    System.out.println("Pre-Persistiting operation: " );
}

@PostPersist
public void postPersist(Message o) {
    System.out.println("Post-Persist operation: " );
}

@PreRemove
public void preRemove(Message o) {
    System.out.println("Pre-Removing operation: " );
}

@PostRemove
public void postRemove(Message o) {
    System.out.println("Post-Remove operation: " );
}

@PreUpdate
public void preUpdate(Message o) {
    System.out.println("Pre-Updating operation: ");
}

@PostUpdate
public void postUpdate(Message o) {
    System.out.println("Post-Update operation: " );
  }
}

Message

  @EntityListeners(MessageListener.class)
  @Entity
  @Table(name = "messages")
public class Message implements Serializable  {

private Integer messageId;

private String subject;

private String content;

public Message(){}

public Message(Integer messageId, String subject, String content) {
    this.messageId = messageId;
    this.subject = subject;
    this.content = content;
}


@Id
@GeneratedValue
@Column(name = "MESSAGE_ID")
public Integer getMessageId() {
    return messageId;
}

//getter setter
@PrePersist
public void prePersist() {
    System.out.println("OLDUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU!!!!!!!!!!!!");
}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As per the JPA spec, JPA callbacks/listeners are not called when using JPQL BULK DELETE. They are only called when using the JPA API (em.remove). Similarly the cache and managed entity objects do not reflect such a JPQL BULK DELETE call.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...