[JPA_SPEC-24] Possibility to inject an EntityManager into an Entity Created: 16/May/12  Updated: 30/Oct/12  Resolved: 30/Oct/12

Status: Closed
Project: jpa-spec
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major
Reporter: AndreasBauer Assignee: Unassigned
Resolution: Works as designed Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Tags: EntityManager, injection


Hello Group,

we are currently confronted with the following scenario:
A legacy database schema has a special table that holds Table-names and associated IDs.
This table's data differs from one database instance to the other.
In order to write data to any other table of the database, this table's ID is needed -> look-up in the ID-table.
To reflect this behavior in a JPA-mapped environment, we wanted each entity to look up its ID in the ID-table before persisting.
But therefore we'd need a reference to an EntityManager from within an Entity.
Our solution: make it possible to inject an EntityManager into an Entity.

Best Regards,

Andreas Bauer

Comment by Mark Struberg [ 20/May/12 ]

If you really go down this route, then expect a few more problems. Doing a select in a @PrePersiste might lead to a flush() which in turns changes your EM. So what you end up is (implicitly) trying to change your current transaction while you're at committing it...

Imo the only sane usage of having a (manually accessible) EntityManager inside an Entity is when it writes to a completely different database (PU). I've seen this for doing changeLog tracking (but this is actually not much superior than a native transaction log). Operating on the same PU will in most cases end up being non-portable ... if you ever manage to survive he operation without Exception on your system.

Comment by ldemichiel [ 30/Oct/12 ]

Well, in Java EE environments, the lifecycle callbacks share the naming context of the calling component, so I suppose you could look up the entity manager in JNDI anyway. That said, the consensus of the group has been that injection of an entity manager into an entity should not be supported. I am therefore closing out this issue.

Generated at Wed Mar 29 06:59:19 UTC 2017 using JIRA 6.2.3#6260-sha1:63ef1d6dac3f4f4d7db4c1effd405ba38ccdc558.