[hibernate-dev] unwrap (was Re: Hibernate Search 3.4 release train)

Scott Marlow smarlow at redhat.com
Thu Feb 17 09:14:15 EST 2011

On 02/17/2011 03:52 AM, Emmanuel Bernard wrote:
> On Feb 16, 2011, at 6:21 PM, Scott Marlow wrote:
>> Its a minor change but I would like to make a small enhancement to
>> EntityManager.unwrap().  I would like to support SessionFactory in case
>> I want to use it later in AS7...
> I guess the alternatives are:
>   - entityManager.unwrap(SessionFactory.class) //not implemented
>   - entityManager.unwrap(Session.class).getSessionFactory()
>   - ( (HibernateEntityManagerFactory) entityManager.getEntityManagerFactory() )
> As you know, I don't feel like an EM should spit *Factories via the unwrap method. So for me option #2 is good enough.

Yeah, applications should be able to use option #2.  My question is 
really about the injection from a PU into a Hibernate SessionFactory. 
Should I also use option #2 internally or wait until EMF.unwrap() is an 
option in the future and use that for my injection support?

I'm trying to avoid breaking applications that might be injecting a PU 
into a Hibernate SessionFactory.

I could do this in stages:

Stage 1:  PU injection would check if the left hand side (target) class 
is a Hibernate SessionFactory and handle that with special code.

Stage 2:  PU injection would use EMF.unwrap(LeftHandSideTarget.class) 
when the JPA specification supports this in the future.

>> Is this completely silly or just mildly silly?  If creating a container
>> managed entity manager doesn't consume a database connection.  I propose
>> that its just mildly silly.  If its just mildly silly, I might want to
>> use the unwrap functionality to keep the AS injection code generic
>> (covering injecting a PU into a Hibernate SessionFactory).  Of course,
>> the other silly part is the idea that I would get an EM from the PU
>> (could lead to unexpected errors if something goes wrong).
> I am a bit uncertain on what you want to achieve.

A generic (dynamic) way to inject (PU/PC) into any PersistenceProvider 
supported class.

At this point, I'm probably better off waiting for 
EntityManagerFactory.unwrap support to be added to the spec (rather than 
hacking it into EM.unwrap(SessionFactory.Class).  Than, we can do the PU 
-> SessionFactory properly.

> Do you want to create a EM that you will not use just to get the SessionFactory?
> I'm not sure I like that very much and I would use option #3 to get the SessionFactory from the EMF.
> Yes the code requires a cast but you depend on Hibernate classes anyway when you need a SessionFactory.

I think just living with "Stage 1" from above is good enough for AS 7.

>> It might be nice to have an unwrap method on the EntityManagerFactory
>> for this purpose.  Is that worth proposing for a future JPA release?
> Yep, it's going to be added.

More information about the hibernate-dev mailing list