0

I have a JPA entity like this:

@SomeCDIInterceptorBinding
@Entity
public class Foo { ... }

Obviously the interceptor doesn't work, since JPA returns an entity instance and not the appropriate CDI proxy. So how do I get an instance of a CDI proxy of my entity, so that method calls invoke my interceptor?

This is specifically a 'how' question. There are other ways to solve my problem, but I want to know whether and how this specific thing is possible.

Answers appreciated.

Dracam
  • 149
  • 2
  • 11

3 Answers3

1

Just stumbled over this post: It can be done quite simply via:

Foo cdiProxy = CDI.current().select(Foo.class).get();

Compare: How to programmatically inject a Java CDI managed bean into a local variable in a (static) method

This way also the interceptor will work. However (important drawback): You manually need to clone the entity's content two times: First on creation and a second time before persiting - as JPA can (to my understanding) not persist CDI proxies.

This, by the way is the reason I found this post. I wonder if there is any way to create 'persistable' CDI proxies. This would make the entity interception work like a charm. And why could't JPA persist CDI proxies anyhow? They should be 'fully transparent'...

Marcus
  • 71
  • 5
0

That's not possible because the entities are managed by the JPA implementation like Hibernate and not by CDI.

Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
0

I think you are confusing the Managed-State of a JPA-Bean with a technical detail of the JPA-Implementation. Entities can be created using new. That means they can not be proxied. So new entities are initially unmanaged. To make them managed, you can use EntityManager.persist or EntityManager.merge, but that also does not mean, that the bean is proxied. It just means that the bean is known (normally by it's Primary Key) to the JPA-Context. If you change a managed entity, these changes will be persisted at the end of the current transaction without further handling.

Proxies you will probably encounter when you look at reference- or collection-fields of entitybeans. They help with lazy-loading and keeping track of changes during a transaction.

aschoerk
  • 3,333
  • 2
  • 15
  • 29