SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-002设置JPA的EntityManagerFactory(<persistence-unit>、<jee:jndi-lookup>)

一、EntityManagerFactory的种类

1.The JPA specification defines two kinds of entity managers:

 Application-managed—Entity managers are created when an application directly requests one from an entity manager factory. With application-managed entity managers, the application is responsible for opening or closing entity managers
and involving the entity manager in transactions. This type of entity manager is most appropriate for use in standalone applications that don’t run in a Java EE container.
 Container-managed—Entity managers are created and managed by a Java EE container. The application doesn’t interact with the entity manager factory at all. Instead, entity managers are obtained directly through injection or from
JNDI . The container is responsible for configuring the entity manager factories.This type of entity manager is most appropriate for use by a Java EE container that wants to maintain some control over JPA configuration beyond what’s specified in persistence.xml.

2.Each flavor of entity manager factory is produced by a corresponding Spring factory bean:

 LocalEntityManagerFactoryBean produces an application-managed EntityManagerFactory .
 LocalContainerEntityManagerFactoryBean produces a container-managed EntityManagerFactory

二、设置方法 

Application-managed entity-manager factories derive most of their configuration information from a configuration file called persistence.xml. This file must appear in the META-INF directory in the classpath.The purpose of the ersistence.xml file is to define one or more persistence units.A persistence unit is a grouping of one or more persistent classes that correspond to a single data source.

 1.xml 

 1 <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
 2     <persistence-unit name="spitterPU">
 3         <class>com.habuma.spittr.domain.Spitter</class>
 4         <class>com.habuma.spittr.domain.Spittle</class>
 5         <properties>
 6             <property name="toplink.jdbc.driver" value="org.hsqldb.jdbcDriver" />
 7             <property name="toplink.jdbc.url" value="jdbc:hsqldb:hsql://localhost/spitter/spitter" />
 8             <property name="toplink.jdbc.user" value="sa" />
 9             <property name="toplink.jdbc.password" value="" />
10         </properties>
11     </persistence-unit>
12 </persistence>

在另一个例子中

 1 <?xml version="1.0"?>
 2 <persistence xmlns="http://java.sun.com/xml/ns/persistence"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
 5     http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
 6   <persistence-unit name="jun" transaction-type="RESOURCE_LOCAL">
 7       <provider>org.hibernate.ejb.HibernatePersistence</provider>
 8     <properties>
 9          <property name="hibernate.dialect" 
10              value="org.hibernate.dialect.MySQLDialect"/><!--数据库方言-->
11          <property name="hibernate.connection.driver_class" 
12              value="com.mysql.jdbc.Driver"/><!--数据库驱动类-->
13          <property name="hibernate.connection.username" value="root"/><!--数据库用户名-->
14          <property name="hibernate.connection.password" value="admin"/>
15          <property name="hibernate.connection.url" 
16              value="jdbc:mysql://localhost:3306/quote;"/><!--数据库连接URL-->
17          <property name="hibernate.max_fetch_depth" value="3"/><!--外连接抓取树的最大深度 -->
18          <property name="hibernate.hbm2ddl.auto" value="update"/><!-- 自动输出schema创建DDL语句 -->
19          <property name="hibernate.jdbc.fetch_size" value="18"/><!-- JDBC的获取量大小 -->
20          <property name="hibernate.jdbc.batch_size" value="10"/><!-- 开启Hibernate使用JDBC2的批量更新功能  -->
21          <property name="hibernate.show_sql" value="true"/><!-- 在控制台输出SQL语句 -->
22       </properties>
23   </persistence-unit>
24 </persistence>

然后bean.xml如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:aop="http://www.springframework.org/schema/aop"
 6        xmlns:tx="http://www.springframework.org/schema/tx"
 7        xsi:schemaLocation="http://www.springframework.org/schema/beans
 8            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 9            http://www.springframework.org/schema/context
10            http://www.springframework.org/schema/context/spring-context-2.5.xsd
11            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
12            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
13     <!-- 配置哪些包下的类需要自动扫描 -->
14     <context:component-scan base-package="com.sanqing"/>    
15    
16     <!-- 这里的jun要与persistence.xml中的 <persistence-unit name="jun" transaction-type="RESOURCE_LOCAL">
17     中的name值要一致,这样才能找到相关的数据库连接
18      -->
19    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
20          <property name="persistenceUnitName" value="jun"/>
21    </bean>  
22    <!-- 配置事物管理器 --> 
23    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
24         <property name="entityManagerFactory" ref="entityManagerFactory"/>
25    </bean>
26    <!-- 配置使用注解来管理事物 -->
27    <tx:annotation-driven transaction-manager="transactionManager"/>
28     
29 </beans>

2.java

1 @Bean
2 public LocalEntityManagerFactoryBean entityManagerFactoryBean() {
3     LocalEntityManagerFactoryBean emfb = new LocalEntityManagerFactoryBean();
4     emfb.setPersistenceUnitName("spitterPU");
5     return emfb;
6 }

The reason much of what goes into creating an application-managed EntityManagerFactory is contained in persistence.xml has everything to do with what it means to be application-managed. 

3.Container-managed JPA takes a different approach. When running in a container, an EntityManagerFactory can be produced using information provided by the container—Spring, in this case.Instead of configuring data-source details in persistence.xml, you can configure this information in the Spring application context.

 1 @Bean
 2 public LocalContainerEntityManagerFactoryBean entityManagerFactory(
 3     DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
 4     LocalContainerEntityManagerFactoryBean emfb =
 5         new LocalContainerEntityManagerFactoryBean();
 6     emfb.setDataSource(dataSource);
 7     emfb.setJpaVendorAdapter(jpaVendorAdapter);
 8     return emfb;
 9 }
10 
11 @Bean
12 public JpaVendorAdapter jpaVendorAdapter() {
13     HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
14     adapter.setDatabase("HSQL");
15     adapter.setShowSql(true);
16     adapter.setGenerateDdl(false);
17     adapter.setDatabasePlatform("org.hibernate.dialect.HSQLDialect");
18     return adapter;
19 }

4.The primary purpose of the persistence.xml file is to identify the entity classes in a persistence unit. But as of Spring 3.1, you can do that directly with LocalContainerEntityManagerFactoryBean by setting the packagesToScan property: 

 1 @Bean
 2 public LocalContainerEntityManagerFactoryBean entityManagerFactory(
 3     DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
 4     LocalContainerEntityManagerFactoryBean emfb =
 5         new LocalContainerEntityManagerFactoryBean();
 6     emfb.setDataSource(dataSource);
 7     emfb.setJpaVendorAdapter(jpaVendorAdapter);
 8     emfb.setPackagesToScan("com.habuma.spittr.domain");
 9     return emfb;
10 }

 there’s no need to configure details about the database in persistence.xml. Therefore,there’s no need for persistence.xml whatsoever! Delete it, and let LocalContainerEntityManagerFactoryBean handle it for you.

  

三、从JNDI中获取EntityManagerFactory

1.xml 

1 <jee:jndi-lookup id="emf" jndi-name="persistence/spitterPU" />

   

2.java 

1 @Bean
2 public JndiObjectFactoryBean entityManagerFactory() {
3     JndiObjectFactoryBean jndiObjectFB = new JndiObjectFactoryBean();
4     jndiObjectFB.setJndiName("jdbc/SpittrDS");
5     return jndiObjectFB;
6 }

 Although this method doesn’t return an EntityManagerFactory , it will result in an EntityManagerFactory bean. That’s because it returns JndiObjectFactoryBean ,which is an implementation of the FactoryBean interface that produces an EntityManagerFactory .

 

原文地址:https://www.cnblogs.com/shamgod/p/5344663.html