我有一个JSF应用程序(Java 8,Wildfly 10,MySQL DB,CDI bean,使用JPA / Hibernate)。大多数类似的问题都与Spring框架有关,或者在我的案例中不起作用。不知道哪些陈述和配置属于Spring,所以我有问题要分开其他可能的解决方案。
通常我的JPA实体工作正常,因为只要我可以使用em.getTransaction.begin()和em.getTransaction.commit(),一切正常。这是我的persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="PU" transaction-type="RESOURCE_LOCAL">
<jta-data-source>java:jboss/datasources/Hanse</jta-data-source>
<class>model.Commodity</class>
<class>model....</class>
<class>model....</class>
<properties>
<!-- <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/> -->
<!-- <property name="hibernate.hbm2ddl.auto" value="update" /> -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<!-- <property name="hibernate.show_sql" value="true" /> -->
<property name="hibernate.enable_lazy_load_no_trans" value="true"/>
</properties>
</persistence-unit>
</persistence>
但我的实体没有持久化,我没有错误或堆栈跟踪。例如:
@Named
@ViewScoped
public class TestController implements Serializable {
private static final long serialVersionUID = -4602041684807072422L;
private String buildDate;
private Ship ship;
@PersistenceContext(unitName = "PU", type = PersistenceContextType.EXTENDED)
private EntityManager em;
@Resource
private UserTransaction utx;
public TestController() {
}
@Transactional
public String doPersistTest() {
this.ship.setRum(this.ship.getRum()+10);
// this.em.getTransaction().begin();
this.em.merge(this.ship);
// this.em.getTransaction().commit();
return "";
}
@PostConstruct
public void init() {
this.ship = (Ship) em.createNamedQuery("Ship.findByID").setParameter("id", 3).getSingleResult();
}
}
db条目不会更改。我也试过
public String doPersistTest() {
this.ship.setRum(this.ship.getRum()+10);
this.em.getTransaction().begin();
this.em.merge(this.ship);
this.em.getTransaction().commit();
return "";
}
并得到错误 WFLYJPA0060:需要事务来执行此操作(使用事务或扩展持久化上下文)(我不解释,有一个事务,我是扩展的持久化上下文)。
如果我尝试
public String doPersistTest() {
this.ship.setRum(this.ship.getRum()+10);
try {
this.utx.begin();
this.em.merge(this.ship);
this.utx.commit();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return "";
}
也没有任何反应。实体不会持久保存到数据库中。我不明白,我的错误是什么?我的JPA“建筑”是否正常。如果没有,有人可以把我推向正确的方向吗?
我也读过