Join Transaction

The EntityManager.joinTransaction() API allows an application managed EntityManager to join the active JTA transaction context. This allows an EntityManager to be created outside the JTA transaction scope and commit its changes as part of the current transaction. This is normally used with a stateful SessionBean, or with a JSP or Servlet where an EXTENDED EntityManager is used in a stateful architecture. A stateful architecture is one where the server stores information on a client connection until the client's session is over, it differs from a stateless architecture where nothing is stored on the server in between client requests (each request is processed on its own).

There are pros and cons with both stateful and stateless architectures. One of the advantages with using a stateful architecture and and EXTENDED EntityManager, is that you do not have to worry about merging objects. You can read your objects in one request, let the client modify them, and then commit them as part of a new transaction. This is where joinTransaction would be used. One issue with this is that you normally want to create the EntityManager when there is no active JTA transaction, otherwise it will commit as part of that transaction. However, even if it does commit, you can still continue to use it and join a future transaction. You do have to avoid using transactional API such as merge or remove until you are ready to commit the transaction.

joinTransaction is only used with JTA managed EntityManagers (JTA transaction-type in persistence.xml). For RESOURCE_LOCAL EntityManagers you can just commit the JPA transaction whenever you desire.

Example joinTransaction usage

EntityManager em = getEntityManagerFactory().createEntityManager();
Employee employee = em.find(Employee.class, id);
employee.setSalary(employee.getSalary() + 1000); UserTransaction transaction = (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction");
transaction.begin();
em.joinTransaction();
transaction.commit();

参考:https://en.wikibooks.org/wiki/Java_Persistence/Transactions

1.示例

@Stateful
public class ShoppingCartImpl implements ShoppingCart {
@PersistenceUnit
private EntityManagerFactory emf;
private EntityManager em;
private Order order;
private Product product;
@PostConstruct
public void init() {
em = emf.createEntityManager();
}
public void initOrder(Long id) {
order = em.find(Order.class, id);
}
public void initProduct(String name) {
product = (Product) em.createQuery("select p from Product p
where p.name = :name")
.setParameter("name", name)
.getSingleResult();
}
public LineItem createLineItem(int quantity) {
em.joinTransaction();
LineItem li = new LineItem(order, product, quantity);
order.getLineItems().add(li);
em.persist(li);
return li;
}
@Remove
public void destroy() {
em.close();
}
}

2.解析

First, a few words of theory...

An application-managed entity manager participates in a JTA transaction in one of two ways.

1. If the persistence context is created inside the transaction, the persistence provider will automatically synchronize

the persistence context with the transaction.
2.If the persistence context was created earlier (outside of a transaction or in a transaction that has since ended), the

persistence context can be manually synchronized with the transaction by calling joinTransaction() on the EntityManager

interface. Once synchronized, the persistence context will automatically be flushed when the transaction commits.

After reading the above definition a few questions may arise:

1.how do we know that ShoppingCartImpl participates in JTA transaction ?

  Because the class has been annotated with @Stateful (or @Stateless) annotation so the intention is to execute the class

within Java EE environment which by default uses JTA transactions. A class doesn't need such annotation, if it will be executed

in Java SE environment.

2.how do we know application-managed entity manager is used in this particular case?

Because we are using @PersistenceUnit annotation to inject EntityManagerFactory and then manually creating and destroying

EntityManager. By doing this we are telling Java EE container that we don't want our transaction to be automatically managed

(like in case of transaction-scoped entity manager or extended entity manager types).

3.why em.joinTransaction() is required in createLineItem method?

By calling em.joinTransaction() we notify the application-managed persistence context that it should synchronize itself with the

current JTA transaction. Without such call the changes to Order would not be flushed to the underlying database when the

transaction commits (at the end of createLineItem method).

NOTE: since EntityManagerFactory instances are thread-safe and EntityManager instances are not, an application must not call

em.joinTransaction() on the same entity manager in multiple concurrent transactions.

引用

http://stackoverflow.com/questions/24442335/use-of-jointransaction-in-jpa

understand EntityManager.joinTransaction()的更多相关文章

  1. Utility3:Understand Dashboard Report

    To see data in the SQL Server Utility dashboard, select the top node in the Utility Explorer tree - ...

  2. JPA中entityManager的CRUD

    private EntityManagerFactory entityManagerFactory; private EntityManager entityManager; private Enti ...

  3. 代码阅读分析工具Understand 2.0试用

    Understand 2.0是一款源代码阅读分析软件,功能强大.试用过一段时间后,感觉相当不错,确实可以大大提高代码阅读效率.由于Understand功能十分强大,本文不可能详尽地介绍它的所有功能,所 ...

  4. 【转载】Understand the serialVersionUID

    If you have ever implemented Serializable interface, you must encounter this warning message The ser ...

  5. understand一些功能

    功能 支持分析的语言 统计总的代码数据 统计单个文件的数据 分析代码复杂度 分析代码格式 文件的依赖关系 文件夹依赖关系 文件夹包含关系.代码量 understand提供了很多图表,同时它可以根据源码 ...

  6. Understand:高效代码静态分析神器详解(转)

    之前用Windows系统,一直用source insight查看代码非常方便,但是年前换到mac下面,虽说很多东西都方便了,但是却没有了静态代码分析工具,很幸运,前段时间找到一款比source ins ...

  7. Five More Hacker Tools Every CISO Should Understand

    As we mentioned in the first article, Top Five Hacker Tools Every CISO Should Understand, the role o ...

  8. Top Five Hacker Tools Every CISO Should Understand

    As the role of the CISO continues to evolve within organizations towards that of an executive level ...

  9. 如何获取EntityManager

    1.在容器内部使用,使用@PersistenceContext 来注入.@PersistenceContextprivate EntityManager em;TAG================= ...

随机推荐

  1. java ssm框架入门(三)正式项目的web.xml配置

    一个正规的上线的web.xml的配置. <?xml version="1.0" encoding="UTF-8"?> <web-app id= ...

  2. Maven实战(插件管理)

    1.前言 近期在做项目中,用到了Maven来管理项目,当理解了Maven的基础知识后,忽然看到好多的插件信息,所以在此总结一下.其有使用方法基本上都一样. 2.源码打包插件 我们能够在Apache的站 ...

  3. C语言 · 最大乘积

      算法提高 最大乘积   时间限制:1.0s   内存限制:512.0MB      问题描述 对于n个数,从中取出m个数,如何取使得这m个数的乘积最大呢? 输入格式 第一行一个数表示数据组数 每组 ...

  4. [Linux]read/write和fread/fwrite有什么区别

    转自:http://blog.csdn.net/xiaofei0859/article/details/51145051 二者都是对文件进行操作,那么二者有什么区别,用的时候该如何选择呢? 1. 区别 ...

  5. Servlet的线程是不是共享同一个requset对象及servlet多线程

    servlet多线程   一,servlet容器如何同时处理多个请求. Servlet采用多线程来处理多个请求同时访问,Servelet容器维护了一个线程池来服务请求.线程池实际上是等待执行代码的一组 ...

  6. 【noip模拟题】日历游戏(博弈论+搜索)

    直接搜索即可... 注意不要爆栈..所以我们可以分块搜索... 然后太懒且太弱我就不写了... orz hzwer http://hzwer.com/4954.html [问题描述] moreD和mo ...

  7. ssh免密码登录的几个注意事项

    1, authorized_keys文件中每个公钥占一行,不能分成多行. 2,文件夹默认权限为600 3,如果遇到奇怪的问题,可以把.ssh/文件全部删掉,重新用ssh-keygen生成.

  8. 一条SQL语句查询两表中两个字段

    首先描述问题,student表中有字段startID,endID.garde表中的ID需要对应student表中的startID或者student表中的endID才能查出grade表中的name字段, ...

  9. Thinkphp新增字段无法插入到数据库问题

    Thinkphp框架开发过程中,因需求需要改动数据表,新增了几个字段. 调用 M(‘xxx’)->add($data) 插入值时,新增的字段数据总是插入不进去,每次都是默认的值,于是恍然—-缓存 ...

  10. 搭建 Docker-Registry 私有仓库

    官方已经提供了很多版本的 Linux 镜像,直接从官方仓库(Public Repositories)下载就可以了.如果考虑到安全性和速度,我们可能会想在自己局域网里架设一个私有仓库(Private R ...