我可以请你在这里寻求帮助。我对容器管理交易如何在幕后工作的知识是有限的,事实上我不知道。我已经看了几个类似于这个问题的其他几个问题,大多数问题都是对Spring的引用,我不使用spring框架,我无法得到解决方案,所以我决定问一下。
我试图在没有使用begin()
和commit()
等明确编写事务代码的情况下获得简单的持久性。我正在使用Hibernate的JPA实现,我使用的app服务器是“WildFly”版本10.1最终版。“我的persistence.xml
看起来如下:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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_1_0.xsd"
version="1.0">
<persistence-unit name="PostgresUnit" transaction-type="JTA">
<class>beans.entity.Customer</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/mydb" />
<property name="javax.persistence.jdbc.user" value="postgres" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="hiberate.flushMode" value="FLUSH_AUTO" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
我有一个实体bean Customer
:
@Entity
@Table ( name = "Customer" )
public class Customer {
@Id
@GeneratedValue ( strategy = GenerationType.IDENTITY )
private int id;
@Column ( unique = true )
private long customerNum;// Domain key attribute.
private String name;
private String surname;
private Date dateOfBirth;
public Customer ( ) {
}
//...getters and setters and so on...
//......
}
我有一个会话bean CustomerService
:
@Local
public interface CustomerService {
void addCustomer( final Customer customer );
}
@Stateless
@TransactionManagement ( TransactionManagementType.CONTAINER )
public class CustomerServiceImpl implements CustomerService {
@Inject
private CustomerResource customerResource; // Injection point using CDI
@Override
public void addCustomer( final Customer customer ) {
customerResource.addCustomer( customer );
}
}
CustomerResource
看起来像这样:
@Local
public interface CustomerResource {
void addCustomer( Customer customer );
}
@ManagedBean // javax.annotation.ManagedBean...
public class CustomerResourceImpl implements CustomerResource {
@PersistenceContext ( unitName = "PostgresUnit" )
private EntityManager entityManager;
@Override
@TransactionAttribute ( TransactionAttributeType.REQUIRED )
public void addCustomer( Customer customer ) {
entityManager.persist( customer );
entityManager.flush();
}
}
当我部署我的应用程序时,我war
的部署成功注入所有依赖项,我通过简单的JSP视图添加客户,因为我一直在使用RESOURCE_LOCAL
事务处理 - 类型(当一切正常时)现在代码运行但没有发生。我没有得到任何例外,客户不会持久存在客户表中。这就像交易甚至没有发生。我在这里缺少什么