understand EntityManager.joinTransaction()
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()的更多相关文章
- Utility3:Understand Dashboard Report
To see data in the SQL Server Utility dashboard, select the top node in the Utility Explorer tree - ...
- JPA中entityManager的CRUD
private EntityManagerFactory entityManagerFactory; private EntityManager entityManager; private Enti ...
- 代码阅读分析工具Understand 2.0试用
Understand 2.0是一款源代码阅读分析软件,功能强大.试用过一段时间后,感觉相当不错,确实可以大大提高代码阅读效率.由于Understand功能十分强大,本文不可能详尽地介绍它的所有功能,所 ...
- 【转载】Understand the serialVersionUID
If you have ever implemented Serializable interface, you must encounter this warning message The ser ...
- understand一些功能
功能 支持分析的语言 统计总的代码数据 统计单个文件的数据 分析代码复杂度 分析代码格式 文件的依赖关系 文件夹依赖关系 文件夹包含关系.代码量 understand提供了很多图表,同时它可以根据源码 ...
- Understand:高效代码静态分析神器详解(转)
之前用Windows系统,一直用source insight查看代码非常方便,但是年前换到mac下面,虽说很多东西都方便了,但是却没有了静态代码分析工具,很幸运,前段时间找到一款比source ins ...
- 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 ...
- 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 ...
- 如何获取EntityManager
1.在容器内部使用,使用@PersistenceContext 来注入.@PersistenceContextprivate EntityManager em;TAG================= ...
随机推荐
- [转]VC传递消息sendmessage
SendMessage的基本结构如下: SendMessage( HWND hWnd, //消息传递的目标窗口或线程的句柄. UINT Msg, //消息类别(这里可以是一些系统消息,也可以是自己定 ...
- 应用DataAdapter对象更新数据库中的数据
using System.Data.SqlClient; namespace WindowsFormsApplication1 { public partial class Form1 : Form ...
- C++ operator关键字(重载操作符)
operator是C++的关键字,它和运算符一起使用,表示一个运算符函数,理解时应将operator=整体上视为一个函数名. 这是C++扩展运算符功能的方法,虽然样子古怪,但也可以理解:一方面 ...
- android monkey app乱点测试
Monkey是Android中的一个命令行工具 查看包名:查看电脑中某一位置的apk文件的包名:PC打开CMD-进入TMG目录-运行设备--查看包名aapt dump badging *.apk(ap ...
- could not find com.android.support.appcompat-v7:23.4.0
导入别人的工程到AS中,出现错误,是由于android studio的版本比所加载的工程所使用的版本低,有些包不是最新的. 我的android studio这个包的版本是 v7:23.1.1 所以需要 ...
- 【BZOJ】1664: [Usaco2006 Open]County Fair Events 参加节日庆祝(线段树+dp)
http://www.lydsy.com/JudgeOnline/problem.php?id=1664 和之前的那题一样啊.. 只不过权值变为了1.. 同样用线段树维护区间,然后在区间范围内dp. ...
- Cocos2d-X中的Slider控件
Slider控件事实上就是滑块控件.经常使用于音乐中的音量控制,在Windows编程中开发音乐播放器就须要用到滑块控件控制音量 首先在project文件夹下的Resource文件夹中放 在Skider ...
- hdu 3336:Count the string(数据结构,串,KMP算法)
Count the string Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...
- Linux服务器的最大内存和CPU数
从网上查了很多资料.总算把linux下的内存和cpu个数搞清楚了.个人觉得使用linux系统的朋友都应该了解下.先公布如下,如有错误,请反馈给我.谢谢!! Linux系统/服务器能够支持的最大内存和C ...
- 漫游Kafka实战篇之搭建Kafka运行环境(2)
接下来一步一步搭建Kafka运行环境. Step 1: 下载Kafka 点击下载最新的版本并解压. > tar -xzf kafka_2.9.2-0.8.1.1.tgz > cd kafk ...