JPA - Persistence与EntityManagerFactory简解

简介: JPA - Persistence与EntityManagerFactory简解

【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)。


目录
相关文章
|
6月前
|
Java 数据库连接
错误org.hibernate.AnnotationException: No identifier specified for entity
请根据你的实际情况,将实体类中的字段和注解进行适当的调整,以确保每个实体类都有一个明确定义的标识符(主键)。 买CN2云服务器,免备案服务器,高防服务器,就选蓝易云。百度搜索:蓝易云
76 0
|
数据库
MybatisPlus dynamic
MybatisPlus dynamic
|
关系型数据库 MySQL 数据库
Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
456 0
|
Java
配置jndi服务,javax.naming.NamingException的四种情况
1.当jndi服务没有启动,或者jndi服务的属性没有设置正确,抛出如下异常: javax.naming.CommunicationException: Can't find SerialContextProvider.
2886 0
|
开发框架 Java 数据库连接
Persistence,EntityManagerFactory和EntityManager
Persistence,EntityManagerFactory和EntityManager
609 0
|
Java 数据库连接
【hibernate】主键生成策略使用UUID报出如下警告:org.hibernate.id.UUIDHexGenerator - HHH000409: Using org.hibernate.id.UUIDHexGenerator which does not generate IETF RFC
主键生成策略使用UUID报出如警告如下: 控制台- 2017-11-24 18:40:14 [restartedMain] WARN org.hibernate.id.UUIDHexGenerator - HHH000409: Using org.
1928 0
|
JSON Java 数据格式
javax.persistence.RollbackException: Transaction marked as rollbackOnly Ask
javax.persistence.RollbackException: Transaction marked as rollbackOnly with Spring MVC.
1634 0
|
Java 数据库连接
【hibernate】错误:org.hibernate.HibernateException: identifier of an instance of com.agen.entity.Monthdetail was altered from xx to xx
所报错误: org.hibernate.HibernateException: identifier of an instance of com.agen.entity.Monthdetail was altered from 40288f8e5ac675fe015ac67725c40001 to ...
1827 0