没有调用JPA Callback

时间:2017-08-02 06:30:00

标签: spring hibernate jpa

我是hibernate的新手。我想知道是否有任何crud操作发生,所以我决定使用jpa回调注释。问题是@PrePersist @PostPersist @PreRemove @PostRemove中的任何一个在我运行项目并使用UI组件执行delete&添加操作。我使用primefaces datatable所以删除操作绑定到ManagedBean - > MessageService - > MessageDAO。如果我只执行主文件来测试它,那就完美了

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

消息监听

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: " );
  }
}

消息

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

}

2 个答案:

答案 0 :(得分:2)

根据JPA规范,使用JPQL BULK DELETE时不会调用JPA回调/侦听器。它们仅在使用JPA API(em.remove)时调用。同样,缓存和托管实体对象也不会反映这样的JPQL BULK DELETE调用。

答案 1 :(得分:0)

通过以下示例更改您的代码希望它能够正常工作

@Transactional
    public void delete(Long id) {

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