我使用apache karaf作为OSGI容器,Aries Blueprint用于声明bean和Hibernate 4.3.6作为JPA提供程序。数据库是MySQL。我需要在抛出异常时回滚事务。我将用以下代码片段来说明它:
@Transactional(Transactional.TxType.REQUIRED)
public void testTransactionMethod() {
Role role = createRole();
roleDao.save(role);
User user = new User();
userDao.save(user);
}
两个DAO的dao.save()方法的实现是:
public T save(T entity) {
return entityManager.merge(entity);
}
DAO的save()
方法未使用@Transactional
进行注释。
我的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"
version="2.0">
<persistence-unit name="examplePersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/sqlds)</jta-data-source>
<properties>
<property name="hibernate.connection.url" value="jdbcURL"/>
<property name="hibernate.connection.username" value="username"/>
<property name="hibernate.connection.password" value="password"/>
<property name="hibernate.connection.driver_class" value="DriverClass"/>
<property name="hibernate.dialect" value="DB_Dialect"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.hbm2ddl.auto" value="none"/>
</properties>
</persistence-unit>
</persistence>
我期望的是当userDao.save(user)
抛出异常时,整个事务将被回滚并且没有在我的ROLE表中保存任何内容,但实际上我的数据库中有一个新的Role条目。
我也尝试使用@Transactional(rollbackOn = Exception.class)
,但仍然得到相同的结果。
修改
根据要求,我添加了我的dataSource cofiguration。我使用pax-jdbc。我有两个cfg文件。第一个是org.apache.aries.jpa.examplePersistenceUnit.cfg
hibernate.connection.url = jdbc:mysql://url/schema
hibernate.connection.username = username
hibernate.connection.password = password
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.hbm2ddl.auto = none
第二个是org.ops4j.datasource-example.cfg
osgi.jdbc.driver.name = mysql
databaseName = ${user.name}
dataSourceName = jdbc/sqlds
url=jdbc:mysql://url/schema
user=${user.name}
password=${user.name}
同样在我的蓝图中,我有以下内容:
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://aries.apache.org/xmlns/jpa/v2.0.0"
xmlns:tx="http://aries.apache.org/xmlns/transactions/v2.0.0"
xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">
<jpa:enable />
<tx:enable />