Pergunta

I have an entity class in my Enterprise Java application that has an entity listener attached to it:

@Entity
@EntityListeners(ChangeListener.class)
public class MyEntity {

   @Id
   private long id;

   private String name;

   private Integer result;

   private Boolean dirty;

   ...
}

However, I would like it so that the entity listener got triggered for all fields except the boolean one. Is there any way exclude a field from triggering the entity listener without making it transient?

I'm using Java EE 5 with Hibernate.

Foi útil?

Solução

There is some kind of mixing of concepts here. EntityListeners are not notified about changes in attribute values - not for single attribute, neither for all attributes.

For reason they are called lifecycle callbacks. They are triggered by following lifecycle events of entity:

  • persist (pre/post)
  • load (post)
  • update(pre/post)
  • remove (pre/post)

For each one of them there is matching annotation. So answer is that it is not possible to limit this functionality by type of persistent attributes.

Outras dicas

However, it is possible if you implement your own solution. I've had the same need for audit log business requirement, so designed my own AuditField annotation, and applied to the fields to be audit-logged.

Here's the example in one entity bean - Site.

@AuditField(exclude={EntityActionType.DELETE})
@Column(name = "site_code", nullable = false)
private String siteCode;

So, the example indicates the 'siteCode' is a field to audit log, except DELETE action. (EntityActionType is an enum and it contains CRUD operations.)

Also, the EntityListenerhas this part of code.

@PostPersist
public void created(Site pEntity) {
log(pEntity, EntityActionType.CREATE);
}

@PreUpdate
public void updated(Site pEntity) {
log(pEntity, EntityActionType.UPDATE);
}

@PreRemove
public void deleted(Site pEntity) {
log(pEntity, EntityActionType.DELETE);
}

Now what it has to do in log() is, to figure what fields are to audit log and what custom actions are involved optionally.

However, there's another to consider. If you put the annotation at another entity variable, what fields of the entity have to be logged? (i.e. chained logging)

It's your choice whether what are annotated with @AuditField only in the entity or some other ways. For my case, we decided to log only the entity ID, which is a PK of a DB table. However, I wanted to make it flexible assuming the business can change. So, all the entites must implement auditValue() method, which is coming from a base entity class, and the default implementation (that's overridable) is to return its ID.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top