Persistence createEntityManagerFactory方法使用
Persistence创建EntityManagerFactory
javax.persistenc.Persistence类提供了两个手动创建EntityManagerFactory对象的方法,它们的定义如下所示。
package javax.persistence;
import java.util.*;
public class Persistence {
/**
* 指定持久化单元,创建EntityManagerFactory对象
* @param persistenceUnitName 持久化单元的名称
*/
public static EntityManagerFactory createEntityManagerFactory(
String persistenceUnitName) {...}
/**
*指定持久化单元和实现者的属性配置,创建EntityManagerFactory对象
*
* @param persistenceUnitName持久化单元的名称
* @param 实现者的属性配置,这些配置将覆盖persistence.xml文件中的配置
*/
public static EntityManagerFactory createEntityManagerFactory(
String persistenceUnitName, Map properties) {...}
}
其中,createEntityManagerFactory(String persistenceUnitName, Map properties)方法中properties的参数将覆盖persistence.xml文件配置的参数。
例如persistence.xml中的<property>元素中的配置如下所示。
<?xml version="1.0" encoding="UTF-8"?>
<persistence>
<persistence-unit name="jpaUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>子
<property name = "hibernate.connection.driver_class" value = "com.mysql. jdbc.Dr iver"/>
<property name = "hibernate.connection.url" value = "jdbc:mysql: //localhost:3306/jp ademo"/>
<property name = "hibernate.connection.username" value = "root"/>
</properties>
<property name="hibernate.show_sql" value="true" />
</persistence-unit>
</persistence>
其中,属性 hibernate.show_sql的值为true,若创建EntityManagerFactory对象时采用以下的代码,则实际获得的 EntityManagerFactory对象属性hibernate.show_sql则为false,即为代码中所设置的将覆盖配置文件中所配置的,如下所示。
Map properties = new HashMap();
properties.put("hibernate.show_sql", "false");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpaUnit", properties);
来自 <http://www.myexception.cn/software-architecture-design/882874.html>