一、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

 <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="spitterPU">
<class>com.habuma.spittr.domain.Spitter</class>
<class>com.habuma.spittr.domain.Spittle</class>
<properties>
<property name="toplink.jdbc.driver" value="org.hsqldb.jdbcDriver" />
<property name="toplink.jdbc.url" value="jdbc:hsqldb:hsql://localhost/spitter/spitter" />
<property name="toplink.jdbc.user" value="sa" />
<property name="toplink.jdbc.password" value="" />
</properties>
</persistence-unit>
</persistence>

在另一个例子中

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

然后bean.xml如下:

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 配置哪些包下的类需要自动扫描 -->
<context:component-scan base-package="com.sanqing"/> <!-- 这里的jun要与persistence.xml中的 <persistence-unit name="jun" transaction-type="RESOURCE_LOCAL">
中的name值要一致,这样才能找到相关的数据库连接
-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="jun"/>
</bean>
<!-- 配置事物管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 配置使用注解来管理事物 -->
<tx:annotation-driven transaction-manager="transactionManager"/> </beans>

2.java

 @Bean
public LocalEntityManagerFactoryBean entityManagerFactoryBean() {
LocalEntityManagerFactoryBean emfb = new LocalEntityManagerFactoryBean();
emfb.setPersistenceUnitName("spitterPU");
return emfb;
}

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.

 @Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean emfb =
new LocalContainerEntityManagerFactoryBean();
emfb.setDataSource(dataSource);
emfb.setJpaVendorAdapter(jpaVendorAdapter);
return emfb;
} @Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase("HSQL");
adapter.setShowSql(true);
adapter.setGenerateDdl(false);
adapter.setDatabasePlatform("org.hibernate.dialect.HSQLDialect");
return adapter;
}

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:

 @Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean emfb =
new LocalContainerEntityManagerFactoryBean();
emfb.setDataSource(dataSource);
emfb.setJpaVendorAdapter(jpaVendorAdapter);
emfb.setPackagesToScan("com.habuma.spittr.domain");
return emfb;
}

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

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

2.java

 @Bean
public JndiObjectFactoryBean entityManagerFactory() {
JndiObjectFactoryBean jndiObjectFB = new JndiObjectFactoryBean();
jndiObjectFB.setJndiName("jdbc/SpittrDS");
return jndiObjectFB;
}

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 .

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

  1. SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-006Spring-Data的运行规则(@EnableJpaRepositories、<jpa:repositories>)

    一.JpaRepository 1.要使Spring自动生成实现类的步骤 (1)配置文件xml <?xml version="1.0" encoding="UTF- ...

  2. SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-003编写JPA-based repository( @PersistenceUnit、 @PersistenceContext、PersistenceAnnotationBeanPostProcessor)

    一.注入EntityManagerFactory的方式 package com.habuma.spittr.persistence; import java.util.List; import jav ...

  3. SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-001-使用Hibernate(@Inject、@EnableTransactionManagement、@Repository、PersistenceExceptionTranslationPostProcessor)

    一.结构 二.Repository层 1. package spittr.db; import java.util.List; import spittr.domain.Spitter; /** * ...

  4. SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-005Spring-Data-JPA例子的代码

    一.结构 二.Repository层 1. package spittr.db; import java.util.List; import org.springframework.data.jpa. ...

  5. SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-004JPA例子的代码

    一.结构 二.Repository层 1. package spittr.db; import java.util.List; import spittr.domain.Spitter; /** * ...

  6. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)

    一. 1.Spring MVC provides several ways that a client can pass data into a controller’s handler method ...

  7. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-005- 异常处理@ResponseStatus、@ExceptionHandler、@ControllerAdvice

    No matter what happens, good or bad, the outcome of a servlet request is a servlet response. If an e ...

  8. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-003- 上传文件multipart,配置StandardServletMultipartResolver、CommonsMultipartResolver

    一.什么是multipart The Spittr application calls for file uploads in two places. When a new user register ...

  9. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener

    一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...

随机推荐

  1. Java通过反射机制修改类中的私有属性的值

    首先创建一个类包含一个私有属性: class PrivateField{ private String username = "Jason"; } 通过反射机制修改username ...

  2. 四则运算(2)之软件单元测试:Right-BICEP

    一.Right-BICEP主要测试以下几方面的问题: Right-结果是否正确? B-是否所有的边界条件都是正确的? I-能查一下反向关联吗? C-能用其他手段交叉检查一下结果吗? E-你是否可以强制 ...

  3. quartz2D简单使用

    quartz2D绘图 1:上下文:context,这个翻译不好理解,其实翻译环境更好一点,就是给了你一个画板,你看不到而已 在: CGContextRef ctx = UIGraphicsGetCur ...

  4. xml基础学习笔记04

    今天继续xml学习,主要是:SimpleXML快速解析文档.xml与数组相互转换 .博客中只是简单的做一个学习记录.积累.更加详细的使用方法,可以查看php手册 1.SimpleXML快速解析文档 前 ...

  5. linux打包压缩命令汇总

    tar命令 [root@linux ~]# tar [-cxtzjvfpPN] 文件与目录 ....参数:-c :建立一个压缩文件的参数指令(create 的意思):-x :解开一个压缩文件的参数指令 ...

  6. 小技巧--字符串输入从a[1]开始

    char a[100],b[100]; cin>>a>>(b+1);//cin: abcd abcd cout<<a[1]<<endl<<b ...

  7. 手机开发Android模拟器genymotion

    手机开发的时候总会碰到一个问题,eclipse插件自带的android模拟器太慢了. 根据网络上有人推荐使用genymotion模拟器.   主要的操作步骤如下: 1.在genymotion网站注册账 ...

  8. DOM中事件绑定补充方法

    先将上一篇文章中提到的为元素增加事件的方法和移除事件的方法拿过来: <span style="font-size:18px;">//跨浏览器添加事件 function ...

  9. 【UOJ Easy Round #2】

    然而UER我也照样跪…… 第一题 忘了取模sad || 操作符将整个区间分成了一些段,每个手机只会执行其中某一段,执行次数为这一段中&&的个数?+1? ans=ans*num[i]+1 ...

  10. A*(A星)算法Go lang实现

    之前发表一个A*的python实现,连接:点击打开链接 最近正在学习Go语言,基本的语法等东西已经掌握了.但是纸上得来终觉浅,绝知此事要躬行嘛.必要的练手是一定要做的.正好离写python版的A*不那 ...