Question

I'm sure this is strongly related to this question but the op on that question has a bit of a scenario that I'm not sure even makes sense for DI. So here's what I understand, it's generally not a good idea to try to mix a JPA Entity with a CDI Bean because both are generally done by creating proxy objects. Here's what I envisioned, but from what I've read this is not possible.

@Entity
public class MyUniqueObject implements Serializable {

    @Inject
    private transient Logger log;

    @Inject
    private transient Event<MyUniqueObjectEvent> events;

    @Id
    private long id;

    @NotNull
    private String text;

    public void setText( final String text ) {
       log.debug( "updating text {}", this );
       this.text = text;
       events.fire( new MyUniqueObjectEvent( this ) ); // consumed by an @Observes method
    }
}

What's the best way to do what I'm trying to accomplish? which is fundamentally things like events firing from within JPA persisted entities, access to log objects. Code examples helpful.

Was it helpful?

Solution

I am wondering if it's really useful to observe every change to entity attributes, even if they won't eventually get persisted. So don't you think that Entity Listeners and Callbacks woudn't be sufficient for you?They support CDI since JPA 2.1 and offer plenty of callbacks which you can observe

  • @PrePersist
  • @PreRemove
  • @PostPersist
  • @PostRemove
  • @PreUpdate
  • @PostUpdate
  • @PostLoad

So you will get

@EntityListeners(class=Audit.class)
@Entity
public class MyUniqueObject implements Serializable {}


public class Audit {

    @Inject
    private Logger log;

    @Inject
    private Event<MyUniqueObjectEvent> events;

}

Now you can observe the lifecycle of your entity - also it's better that you have separated your model and its auditing, you don't have to mess up with setters and getters (which is confusing) to achieve logging. Also note that you can also define Default Entity Listeners for every entity you have.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top