gpt4 book ai didi

java - 使用 JPA/JTA/JBOSS/CDI 不会持久化对象

转载 作者:行者123 更新时间:2023-11-29 09:48:01 28 4
gpt4 key购买 nike

请帮助我理解为什么对象没有通过以下代码持久化。它抛出 javax.persistence.TransactionRequiredException: JBAS011469: Transaction is required to perform this operation (either use a transaction or extended persistence context)

public class OrganizationRepositoryImpl implements OrganizationRepository {

@PersistenceContext(unitName="usermanagement",type=PersistenceContextType.TRANSACTION)
private EntityManager em;

public void save(Organization organization) {
try {
em.persist(organization);
}catch(Exception e) {
e.printStackTrace();

}
}
}

但是如果我用@Stateless注解(现在是ejb)来注解类,对象就会开始持久化

@Stateless    
public class OrganizationRepositoryImpl implements OrganizationRepository {

@PersistenceContext(unitName="usermanagement",type=PersistenceContextType.TRANSACTION)
private EntityManager em;

public void save(Organization organization) {
try {
em.persist(organization);
}catch(Exception e) {
e.printStackTrace();

}
}
}

persistence.xml

    <?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="usermanagement" transaction-type="JTA">
<jta-data-source>java:jboss/datasources/MysqlXADS</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>
<property name="jboss.entity.manager.factory.jndi.name" value="java:jboss/myEntityManagerFactory" />
</properties>
</persistence-unit>
</persistence>

服务类调用Repository将对象持久化到数据库

    public class OrganizationServiceImpl implements OrganizationService {

@Inject
private OrganizationRepository orgRepo;

public Response createOrganization(InputStream is) {
Organization org = null;
org = readStream(is);
orgRepo.save(org);
return Response.created(URI.create("/organizations/" + org.getId()))
.build();
}

private Organization readStream(InputStream is) {
JAXBContext context;
Organization org = null;
try {
context = JAXBContext.newInstance(Organization.class);
Unmarshaller um = context.createUnmarshaller();
org = (Organization) um.unmarshal(is);
} catch (JAXBException e) {
e.printStackTrace();
}
return org;
}
}

最佳答案

当您将 bean 声明为 @Stateless 时,该 bean 中的方法默认是事务性的。事务性方法在完全执行时提交持久性状态。

如果您的类没有使用 @Stateless 注释,默认情况下方法不是事务性的,因此您会遇到上述异常。

关于java - 使用 JPA/JTA/JBOSS/CDI 不会持久化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23300014/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com