JBoss daily recipe

If you have need to use callback methods in your EJB Entity Beans then it's likely that your code is a mess! With EJB 3.0 you can add the  @EntityListeners annotation to indicate that the callback methods are located in another class.

Example: recall the Note class in the EJB 3.0 tutorial:



import java.io.Serializable;     
import javax.persistence.Entity;   
import javax.persistence.GeneratedValue;   
import javax.persistence.Id;   
import javax.persistence.Table;   
@Table(name = "NOTE")   
public class Note implements Serializable {   
long noteId;   
String text;   
String actor;   
String attachment;   
public long getNoteId() {   
 return noteId;   
public void setNoteId(long noteId) {   
 this.noteId = noteId;   
public String getActor() {   
 return actor;   
public void setActor(String actor) {   
 this.actor = actor;   
public String getAttachment() {   
 return attachment;   
public void setAttachment(String attachment) {   
 this.attachment = attachment;   
public String getText() {   
 return text;   
public void setText(String text) {   
 this.text = text;   

and this is the Class holding the listener:

import javax.persistence.PreRemove;
import javax.persistence.PostRemove;
import javax.persistence.PreUpdate;
import javax.persistence.PostUpdate;
import javax.persistence.PostLoad;
import javax.persistence.PrePersist;
import javax.persistence.PostPersist;

public class NoteCallbackListener
   public void doPrePersist(Note note)
      System.out.println("doPrePersist: About to create Note: " + Note.getId());

   public void doPostPersist(Object Note)
      System.out.println("doPostPersist: Created Note: " + ((Note)Note).getId()));

   public void doPreRemove(Note note)
      System.out.println("doPreRemove: About to delete Note: " + Note.getId());

   public void doPostRemove(Note note)
      System.out.println("doPostRemove: Deleted Note: " + Note.getId());

   public void doPreUpdate(Note note)
      System.out.println("doPreUpdate: About to update Note: " + Note.getId());

   public void doPostUpdate(Note note)
      System.out.println("doPostUpdate: Updated Note: " + Note.getId());

   public void doPostLoad(Note note)
      System.out.println("doPostLoad: Loaded Note: " + Note.getId());

Related articles available on mastertheboss.com

EJB 3.0 tutorial : Session Beans

Enterprise JavaBeans (EJB) technology is a J2EE technology for de

JBoss MDB 3.0

Message-driven beans (MDBs) are stateless, server-side, transacti


In a Bean Managed Transaction, the code in the EJB or Message Dri

How to set EJB timeout period ?

JBoss recipe of the day

How to add a Selector with MDB 3.0 ?

Message selectors allow an MDB to be more selective about the mes

How to create a MDB 3.0 singleton ?

  EJB3 uses the resource adapter.  When using the resource adapt