一、注入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. 【PHP】iOS推送通知以及反馈服务

    近来项目是完成一个PHP的推送服务器,无论是PHP,APNs还是GCM基本上都是从零开始. 写下一点见解,方便以后继续做代码的搬运工. 因为对PHP跟iOS都不熟悉,可能有错漏...穷孩子没有用过iO ...

  2. Android BLE API: GATT Notification not received

    When setting the value to the descriptor instead of putting descriptor.setValue(BluetoothGattDescrip ...

  3. Java面试之SE基础基本数据类型

    1.九种基本数据类型的大小以及它们的封装类 在我们面试或者考试过程中经常会考到八种基本数据类型以及它们的封装类,那么有哪八种基本数据类型呢?它们的封装类又是什么呢? 首先,八种基本数据类型分别是:in ...

  4. C#开源系统大汇总(转)

    一.AOP框架        Encase 是C#编写开发的为.NET平台提供的AOP框架.Encase 独特的提供了把方面(aspects)部署到运行时代码,而其它AOP框架依赖配置文件的方式.这种 ...

  5. Word图片版式设置问题

    word里面插入图片,版式设置为嵌入式,又显示不完整:设置上下,图片又跑到页面上方空白处.无论怎么设置,都不满意. 以为是word的问题,后来网络搜索才发现,如果段落行距为固定值的话,图片改为嵌入型后 ...

  6. 对MVC的理解

    摘要:本文主要谈到了对PHP开发中MVC开发模式的理解. 当用户通过url触发命令时,例如url=http://control.blog.sina.com.cn/admin/article/artic ...

  7. 学习Linux第七天

    1.shell echo $HOME 默认在shell中编写的变量全部是局部变量,如果重新打开console的话,那么这些变量将全部丢失,全局的变量可以写在文件~/.bashrc文件. 2.判断 !/ ...

  8. Microsoft SQL Server 存储过程举例

    -- if SP is existed, drop it. if (object_id('InvHoldToDPS', 'P') is not null) drop proc InvHoldToDPS ...

  9. 引入代码后,在@override报错

    最近引入了spring的源码到工程里,发现凡是@override修饰的代码都会报错 这里有java历史的原因 5及以前不支持@override的注解,所以,此时,你最需要知道的是当前项目djk的编译版 ...

  10. 管理员必须掌握的八个cmd命令

    一.ping   它是用来检查网络是否通畅或者网络连接速度的命令.作为一个生活在网络上的管理员或者黑客来说,ping命令是第一个必须掌握的DOS命令,它所利用的原理是这样的:网络上的机器都有唯一确定的 ...