【1】Persistence类
Persistence 类是用于获取 EntityManagerFactory 实例。
该类包含一个名为 createEntityManagerFactory 的 静态方法 。
createEntityManagerFactory 方法有如下两个重载版本。
- ① 带有一个参数的方法:以 JPA 配置文件 persistence.xml 中的持久化单元名为参数;
- ② 带有两个参数的方法:前一个参数含义相同,后一个参数 Map类型,用于设置 JPA 的相关属性,这时将忽略其它地方设置的属性。Map 对象的属性名必须是 JPA 实现库提供商的名字空间约定的属性名。
//1. 创建 EntitymanagerFactory String persistenceUnitName = "jpa-1"; Map<String, Object> properites = new HashMap<String, Object>(); properites.put("hibernate.show_sql", false); EntityManagerFactory entityManagerFactory = // Persistence.createEntityManagerFactory(persistenceUnitName); Persistence.createEntityManagerFactory(persistenceUnitName, properites);
其源码如下:
// $Id: Persistence.java 20957 2011-06-13 09:58:51Z stliu $ package javax.persistence; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.spi.LoadState; import javax.persistence.spi.PersistenceProvider; import javax.persistence.spi.PersistenceProviderResolverHolder; /** * Bootstrap class that provides access to an EntityManagerFactory. */ public class Persistence { @Deprecated public static final String PERSISTENCE_PROVIDER = "javax.persistence.spi.PeristenceProvider"; @Deprecated protected static final Set<PersistenceProvider> providers = new HashSet<PersistenceProvider>(); /** * Create and return an EntityManagerFactory for the named persistence unit. * * @param persistenceUnitName The name of the persistence unit * * @return The factory that creates EntityManagers configured according to the specified persistence unit */ public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName) { return createEntityManagerFactory( persistenceUnitName, null ); } /** * Create and return an EntityManagerFactory for the named persistence unit using the given properties. * * @param persistenceUnitName The name of the persistence unit * @param properties Additional properties to use when creating the factory. The values of these properties override * any values that may have been configured elsewhere * * @return The factory that creates EntityManagers configured according to the specified persistence unit */ public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) { EntityManagerFactory emf = null; List<PersistenceProvider> providers = getProviders(); for ( PersistenceProvider provider : providers ) { emf = provider.createEntityManagerFactory( persistenceUnitName, properties ); if ( emf != null ) { break; } } if ( emf == null ) { throw new PersistenceException( "No Persistence provider for EntityManager named " + persistenceUnitName ); } return emf; } private static List<PersistenceProvider> getProviders() { return PersistenceProviderResolverHolder .getPersistenceProviderResolver() .getPersistenceProviders(); } /** * @return Returns a <code>PersistenceUtil</code> instance. */ public static PersistenceUtil getPersistenceUtil() { return util; } private static PersistenceUtil util = //TODO add an Hibernate specific optimization new PersistenceUtil() { public boolean isLoaded(Object entity, String attributeName) { List<PersistenceProvider> providers = Persistence.getProviders(); for ( PersistenceProvider provider : providers ) { final LoadState state = provider.getProviderUtil().isLoadedWithoutReference( entity, attributeName ); if ( state == LoadState.UNKNOWN ) continue; return state == LoadState.LOADED; } for ( PersistenceProvider provider : providers ) { final LoadState state = provider.getProviderUtil().isLoadedWithReference( entity, attributeName ); if ( state == LoadState.UNKNOWN ) continue; return state == LoadState.LOADED; } return true; } public boolean isLoaded(Object object) { List<PersistenceProvider> providers = Persistence.getProviders(); for ( PersistenceProvider provider : providers ) { final LoadState state = provider.getProviderUtil().isLoaded( object ); if ( state == LoadState.UNKNOWN ) continue; return state == LoadState.LOADED; } return true; } }; }
【2】EntityManagerFactory 接口
EntityManagerFactory 接口主要用来创建 EntityManager 实例。
该接口主要约定了如下4个方法:
- ① createEntityManager():用于创建实体管理器对象实例。
- ② createEntityManager(Map map):用于创建实体管理器对象实例的重载方法,Map 参数用于提供 EntityManager 的属性。
- ③ isOpen():检查 EntityManagerFactory 是否处于打开状态。实体管理器工厂创建后一直处于打开状态,除非调用close()方法将其关闭。
- ④ close():关闭 EntityManagerFactory 。
EntityManagerFactory 关闭后将释放所有资源,isOpen()方法测试将返回 false,其它方法将不能调用,否则将导致IllegalStateException异常。
其接口源码如下:
// $Id: EntityManagerFactory.java 20957 2011-06-13 09:58:51Z stliu $ package javax.persistence; import java.util.Map; import javax.persistence.metamodel.Metamodel; import javax.persistence.criteria.CriteriaBuilder; /** * Interface used to interact with the entity manager factory * for the persistence unit. * * <p>When the application has finished using the entity manager * factory, and/or at application shutdown, the application should * close the entity manager factory. Once an * <code>EntityManagerFactory</code> has been closed, all its entity managers * are considered to be in the closed state. * * @since Java Persistence 1.0 */ public interface EntityManagerFactory { /** * Create a new application-managed <code>EntityManager</code>. * This method returns a new <code>EntityManager</code> instance each time * it is invoked. * The <code>isOpen</code> method will return true on the returned instance. * @return entity manager instance * @throws IllegalStateException if the entity manager factory * has been closed */ public EntityManager createEntityManager(); /** * Create a new application-managed <code>EntityManager</code> with the * specified Map of properties. * This method returns a new <code>EntityManager</code> instance each time * it is invoked. * The <code>isOpen</code> method will return true on the returned instance. * @param map properties for entity manager * @return entity manager instance * @throws IllegalStateException if the entity manager factory * has been closed */ public EntityManager createEntityManager(Map map); /** * Return an instance of <code>CriteriaBuilder</code> for the creation of * <code>CriteriaQuery</code> objects. * @return CriteriaBuilder instance * @throws IllegalStateException if the entity manager factory * has been closed * * @since Java Persistence 2.0 */ public CriteriaBuilder getCriteriaBuilder(); /** * Return an instance of <code>Metamodel</code> interface for access to the * metamodel of the persistence unit. * @return Metamodel instance * @throws IllegalStateException if the entity manager factory * has been closed * * @since Java Persistence 2.0 */ public Metamodel getMetamodel(); /** * Indicates whether the factory is open. Returns true * until the factory has been closed. * @return boolean indicating whether the factory is open */ public boolean isOpen(); /** * Close the factory, releasing any resources that it holds. * After a factory instance has been closed, all methods invoked * on it will throw the <code>IllegalStateException</code>, except * for <code>isOpen</code>, which will return false. Once an * <code>EntityManagerFactory</code> has been closed, all its * entity managers are considered to be in the closed state. * @throws IllegalStateException if the entity manager factory * has been closed */ public void close(); /** * Get the properties and associated values that are in effect * for the entity manager factory. Changing the contents of the * map does not change the configuration in effect. * @return properties * @throws IllegalStateException if the entity manager factory * has been closed * * @since Java Persistence 2.0 */ public Map<String, Object> getProperties(); /** * Access the cache that is associated with the entity manager * factory (the "second level cache"). * @return instance of the <code>Cache</code> interface * @throws IllegalStateException if the entity manager factory * has been closed * * @since Java Persistence 2.0 */ public Cache getCache(); /** * Return interface providing access to utility methods * for the persistence unit. * @return <code>PersistenceUnitUtil</code> interface * @throws IllegalStateException if the entity manager factory * has been closed * * @since Java Persistence 2.0 */ public PersistenceUnitUtil getPersistenceUnitUtil(); }
总结
- EntityManagerFactory (对应 Hibernate 中的 SessionFactory)。
- EntityManager (对应 Hibernate 中的Session)。