一、注入EntityManagerFactory的方式

 package com.habuma.spittr.persistence;
import java.util.List;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.habuma.spittr.domain.Spitter;
import com.habuma.spittr.domain.Spittle;
@Repository
@Transactional
public class JpaSpitterRepository implements SpitterRepository {
@PersistenceUnit
private EntityManagerFactory emf;
public void addSpitter(Spitter spitter) {
emf.createEntityManager().persist(spitter);
}
public Spitter getSpitterById(long id) {
return emf.createEntityManager().find(Spitter.class, id);
}
public void saveSpitter(Spitter spitter) {
emf.createEntityManager().merge(spitter);
}
...
}

这种方式有一个问题,Aside from presenting a troubling code-duplication situation, it also means a new EntityManager is created every time one ofthe repository methods is called. This complicates matters concerning transactions.

二、注入EntityManager的方式(其实并注入代理)

若用注入EntityManager的方式,也有一个问题,The problem is that an EntityManager isn’t thread-safe and generally shouldn’t be injected into a shared singleton bean like your repository. But that doesn’t mean you can’t ask for an EntityManager anyway.

 package com.habuma.spittr.persistence;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.habuma.spittr.domain.Spitter;
import com.habuma.spittr.domain.Spittle;
@Repository
@Transactional
public class JpaSpitterRepository implements SpitterRepository {
@PersistenceContext
private EntityManager em;
public void addSpitter(Spitter spitter) {
em.persist(spitter);
}
public Spitter getSpitterById(long id) {
return em.find(Spitter.class, id);
}
public void saveSpitter(Spitter spitter) {
em.merge(spitter);
}
...
}

关于线程的安全问题,The truth is that @PersistenceContext doesn’t inject an EntityManager —at least,not exactly. Instead of giving the repository a real EntityManager , it gives a proxy to a real EntityManager . That real EntityManager either is one associated with the current transaction or, if one doesn’t exist, creates a new one. Thus, you know that you’re

always working with an entity manager in a thread-safe way.

@PersistenceUnit and  @PersistenceContext是JPA的标准,要让Spring明白这两个标签的注入方式,则要配置PersistenceAnnotationBeanPostProcessor,但若是使用 <context:annotation-config> or  <context:component-scan> ,则默认是已经配置了的

 @Bean
public PersistenceAnnotationBeanPostProcessor paPostProcessor() {
return new PersistenceAnnotationBeanPostProcessor();
}

@Transactional indicates that the persistence methods in this repository are involved in a transactional context.

SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-003编写JPA-based repository( @PersistenceUnit、 @PersistenceContext、PersistenceAnnotationBeanPostProcessor)的更多相关文章

  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-002设置JPA的EntityManagerFactory(<persistence-unit>、<jee:jndi-lookup>)

    一.EntityManagerFactory的种类 1.The JPA specification defines two kinds of entity managers:  Applicatio ...

  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. APM飞控修改数传模块方法

    APM飞控修改数传模块方法 硬件 ARDUCOPTER第二代 数传模块(USB接口) 数传模块(telem接口) usb-ttl模块 修改方法 注意:APM固件版本和数传模块估计版本是分开的,但有一定 ...

  2. activemq整合spring

  3. 《实时控制软件设计》Git 基本操作练习

    根据老师提供的教程 对 数据库创建.提交文件.创建分支.删除分支.合并分支.冲突处理等操作进行了练习 得到log文件如下: yanbin-guo@yanbinguo MINGW64 /Git (mas ...

  4. xml基础学习笔记03

    继续上篇xml学习笔记,坚持.坚持.再坚持啊.... 本篇主要记录: 35.XML节点的删除与修改 36集.用XML制作RSS订阅源 <?php /* 笔记: 35.XML节点的删除与修改 使用 ...

  5. android开发 ,对接支付宝,服务器(PHP)校验失败

    已备忘记,资料链接: http://my.oschina.net/u/256646/blog/174222 注意: 里面有一个设计到支付宝公钥的地方: 注 意这个是2048位的公钥应该是9行或者10行 ...

  6. The finnacial statements,taxes and cash flow

    This chapter-2 we learn about the the financial statements(财务报表),taxes and cash flow.We must pay par ...

  7. adb 连接时 device offline

    继上一篇博文,会发现最后图片上 adb连接时候提示device offline 以下三种方法可以试一下~我是试到最后一种才成功 1.重启手机 2.adb kill-server    adb star ...

  8. 项目部署之VPN+端口映射

    背景:出差开发项目,需要在客户那里部署基本成型的系统.这套系统需要一个公网的ip地址(一个后台管理系统,使用花生壳提供域名服务.一个公网的tcp server,java io实现),但是客户那里无法提 ...

  9. 2014ACM/ICPC亚洲区广州站 北大命题

    http://acm.hdu.edu.cn/showproblem.php?pid=5131 现场赛第一个题,水题.题意:给水浒英雄排序,按照杀人数大到小,相同按照名字字典序小到大.输出.然后对每个查 ...

  10. C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V110\Microsoft.CppCommon.targets(611,5): error MSB

    project options, linker, manifest, Generate Manifest-> NO. 项目->属性->链接器->清单文件->生成清单  改 ...