繁体   English   中英

CDI Beans和JPA交易

[英]CDI Beans and JPA Transactions

应该用作cdi应用程序作用域的bean是否包含jpa读/写内容?或者我应该始终使用EJB作为db的东西吗? 我在互联网上的某处读到cdi不包含数据库内容。 真的吗?

是的,如果您使用的是任何JavaEE 7 plus版本或JakartaEE ,您可以使用@Transactional InterceptorBinding管理CDI bean上的db 内容

看看Javadoc: @Transactional

以下是使用不带EJB CDI注入EntityManager的步骤

  1. 首先创建一个生成器来生成EntityManager

     public class EntityManagerProducer { @PersistenceContext(name = "customer-orders-unit") private EntityManager em; @Produces @RequestScoped public EntityManager getEntityManager() { return em; } } 
  2. 创建bean来执行DAO操作。

     public MyCDIBeanDao{ @Inject private EntityManager m_entityManager; @Transactional public doStuff(){ // Here you are in a Container managed Transaction m_entityManager.persist(...) } } 
  3. 不要忘记在WEB-INF文件夹中添加beans.xml

     <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd" bean-discovery-mode="all" version="2.0"> </beans> 

一如既往,答案取决于......这取决于您的具体用例。

在Java EE中,我们使用@EJB bean作为我们注入EntityManager的位置,以便稍后在JPA实体上执行读/写操作。 为什么我们这样做? 因为我们需要Transactions 默认情况下,当您使用@Stateless注释bean时,其中的所有方法都是Transactional ,您可以免费获得它。 事务使您能够以原子方式更新多个表,它们将全部成功或失败。

示例:在您的方法updateABC()您希望更新表A,B,C,并且您希望所有这些都成功或者事务是Roll-backed:

@Stateless
public class MyClass{
    @PersistenceContext
    EntityManager em;

    public void updateABC(){
       A a= em.find(A.class, aId);
       //here update some fields on the entity "a"

       B b= em.find(B.class, bId);
       //here update some fields on the entity "b"
       C c= em.find(C.class, cId);
       //here update some fields on the entity "c"
    }
}

这就是它......你已经完成了。 您的所有更新都会神奇地保留在数据库中,或者什么都没有。

你需要这样的东西吗? 去寻找EJB。 你不需要? 你想手动完成这项工作吗? 然后创建自己的豆...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM