Added tutorials of the hibernate-release 5.0.12.Final
[hibernate4-maven-plugin] / src / it / tutorials-5.0.12 / osgi / unmanaged-jpa / src / main / java / org / hibernate / osgitest / HibernateUtil.java
1 /* 
2  * Hibernate, Relational Persistence for Idiomatic Java
3  * 
4  * JBoss, Home of Professional Open Source
5  * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors
6  * as indicated by the @authors tag. All rights reserved.
7  * See the copyright.txt in the distribution for a
8  * full listing of individual contributors.
9  *
10  * This copyrighted material is made available to anyone wishing to use,
11  * modify, copy, or redistribute it subject to the terms and conditions
12  * of the GNU Lesser General Public License, v. 2.1.
13  * This program is distributed in the hope that it will be useful, but WITHOUT A
14  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
15  * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
16  * You should have received a copy of the GNU Lesser General Public License,
17  * v.2.1 along with this distribution; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  * MA  02110-1301, USA.
20  */
21 package org.hibernate.osgitest;
22
23 import javax.persistence.EntityManager;
24 import javax.persistence.EntityManagerFactory;
25 import javax.persistence.spi.PersistenceProvider;
26
27 import org.osgi.framework.Bundle;
28 import org.osgi.framework.BundleContext;
29 import org.osgi.framework.FrameworkUtil;
30 import org.osgi.framework.ServiceReference;
31
32 /**
33  * @author Brett Meyer
34  */
35
36 public class HibernateUtil {
37
38         private EntityManagerFactory emf;
39
40         public EntityManager getEntityManager() {
41                 return getEntityManagerFactory().createEntityManager();
42         }
43
44         private EntityManagerFactory getEntityManagerFactory() {
45                 if ( emf == null ) {
46                         Bundle thisBundle = FrameworkUtil.getBundle( HibernateUtil.class );
47                         // Could get this by wiring up OsgiTestBundleActivator as well.
48                         BundleContext context = thisBundle.getBundleContext();
49
50                         ServiceReference serviceReference = context.getServiceReference( PersistenceProvider.class.getName() );
51                         PersistenceProvider persistenceProvider = (PersistenceProvider) context.getService( serviceReference );
52
53                         emf = persistenceProvider.createEntityManagerFactory( "unmanaged-jpa", null );
54                 }
55                 return emf;
56         }
57 }