我尝试在我的 Spring (v 3.1) Web 应用程序中使用一些在 scala 中编程的 bean,并且在事务方面遇到了奇怪的问题。
我在 Roo 中设置了一个小而完整的 Spring 应用程序来显示我的问题。老实说,我不知道为什么它不起作用......
project --topLevelPackage com.app
jpa setup --provider ECLIPSELINK --database DERBY_EMBEDDED
entity jpa --class com.app.MyEntity
field string --fieldName title
然后我在java中创建了接口
package com.app;
public interface IScalaMainClass {
void doSomething();
}
package com.app;
public interface IScala1 {
void someMethod();
}
package com.app;
public interface IScala2 {
void someMethod();
}
这些实现是在 Scala 中创建的,其中 Scala1 持久化 MyEntity 并且 Scala2 进行 DELETE 查询:
package com.app
import org.springframework.transaction.annotation.Transactional
import org.springframework.stereotype.Repository
import org.springframework.beans.factory.annotation.Autowired
@Repository class ScalaMainClass extends com.app.IScalaMainClass {
@Autowired var bean1: IScala1 = null
@Autowired var bean2: IScala2 = null
@Transactional def doSomething() = {
bean1.someMethod()
bean2.someMethod()
}
}
package com.app
import org.springframework.stereotype.Repository
import javax.persistence.{EntityManager, PersistenceContext}
@Repository class Scala1 extends com.app.IScala1 {
@PersistenceContext var em: EntityManager = null
def someMethod = {
val e = new MyEntity
em persist e
}
}
package com.app
import org.springframework.transaction.annotation.Transactional
import org.springframework.stereotype.Repository
import javax.persistence.{EntityManager, PersistenceContext}
@Repository class Scala2 extends com.app.IScala2 {
@PersistenceContext var em: EntityManager = null
@Transactional def someMethod = {
val q = em createQuery "DELETE FROM MyEntity"
q executeUpdate
}
}
最后创建执行 IScalaMainClass 的 Java 测试:
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.annotation.Rollback;
import org.springframework.beans.factory.annotation.Autowired;
import org.junit.runner.RunWith;
import org.junit.Test;
import org.junit.Assert;
import com.app.IScalaMainClass;
@ContextConfiguration(locations = "classpath:/META-INF/spring/applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(defaultRollback = false)
public class AppTest {
@Autowired private IScalaMainClass smc;
@Test public void testIt() {
smc.doSomething();
}
}
如果您现在将 scala 依赖项添加到 pom.xml 并执行“mvn test”,您将收到
javax.persistence.TransactionRequiredException:
Exception Description: No transaction is currently active
...