【发布时间】:2017-09-14 06:47:08
【问题描述】:
我使用 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 配置。我使用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 />
【问题讨论】:
-
您能展示一下您是如何设置数据源的吗?我认为 DataSource 可能还没有完全准备好 XA。
-
嗨克里斯蒂安!我更新了我的问题以包含配置。
-
检查 MySQL 中表的类型。 MyISAM 还是 InnoDb? stackoverflow.com/questions/8036005/…
-
表类型为 InnoDb。我尝试将其更改为 MyISAM,但没有任何区别。
-
能否提供命令结果:service:list DataSource
标签: mysql hibernate jpa osgi rollback