是否可以创建利用通过@Transactional创建的现有事务的本机查询? 这里的大多数问题似乎都是关于进行本机查询。此外,来自Spring + Hibernate Transaction -- Native SQL rollback failure的答案也表示可能无法做到。
我测试隔离的方法是运行一些删除并添加一个断点来调查数据库。
这是我到目前为止所尝试的内容:
@Transactional(value = "someManager")
public class SpringJpaSomeDao implements SomeDao {
@PersistenceContext(unitName = "someUnit")
@Qualifier("entityManagerFactorySome")
private EntityManager em;
@Resource
@Qualifier("someManager")
private PlatformTransactionManager transactionManager;
@Override
@Transactional(value = "someManager", propagation = Propagation.SUPPORTS)
public void runNative(String sql){
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
em.createNativeQuery(sql).executeUpdate();
}
});
}
persistence.xml的某些部分
<persistence-unit name="someUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>java:comp/env/jdbc/someDS</non-jta-data-source>
<!-- some classes here -->
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<!-- some dialect -->
</properties>
</persistence-unit>
从某个控制器调用代码,该控制器还具有@Transactional注释,用于删除Dao。
@Transactional(value = "someManager", propagation = Propagation.SUPPORTS)
public void deleteEntireDatabase() {
List<String> deletions = new ArrayList<>();
deletions.add("DELETE FROM something;");
for (String currentDeletion : deletions) {
someDao.runNative(currentDeletion);
}
}
@Override
@Transactional(value = "someManager", propagation = Propagation.REQUIRES_NEW, rollbackFor = {Exception.class})
public void deleteAndFill(JobExecutionProgress progress) {
deleteEntireDatabase();
// more code
}
摘自spring-dao.xml:
<tx:annotation-driven />
<bean id="entityManagerFactorySome" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="someDataSource" />
<property name="persistenceUnitName" value="someUnit" />
<property name="jpaProperties">
<props>
<!-- some dialect -->
</props>
</property>
</bean>
<bean id="someDao" class="xyz.model.controller.SpringJpaSomeDao"/>
<bean id="someManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactorySome" />
<qualifier value="someManager"></qualifier>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
当然,我还尝试了一些变体,例如不同的传播,并使用从其他地方获得的entityManager:
EntityManagerFactory emf = ((JpaTransactionManager) transactionManager).getEntityManagerFactory();
EntityManager em2 = EntityManagerFactoryUtils.getTransactionalEntityManager(emf);
现在,如果其他一切都失败了,我会做的是手动交易管理。
这是适用于您的某个应用程序的内容还是未知是否可能是设置问题?
答案 0 :(得分:0)
实际上,事实证明,评论中提到的alter table语句似乎是问题所在。不确定重置auto_increment如何清空表,但似乎就是这种情况。