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 实例。

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流烟默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值