[英]Play transactions with Hibernate
我正在将Play版本2.2与Hibernate一起使用。 我正在尝试创建另一个“层”来管理数据库操作,我是否必须在其中包装每个事务,或者是否有其他更优雅的方法来做到这一点,我必须做出变通办法来访问传递给方法的变量。
JPA.withTransaction(new F.Callback0() {
@Override
public void invoke() throws Throwable {
...
JPA.em().persist(someObject);
...
}
});
使用注释@Transactional
在这个例子中,我使用aspjectj来包装用自定义注释标记的方法来应用JPA事务: github示例 。
插件.sbt
logLevel := Level.Warn
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.2.1")
// Used to weave Logger calls in Controllers and service
addSbtPlugin("com.typesafe.sbt" % "sbt-aspectj" % "0.9.4")
build.scala
import com.typesafe.sbt.SbtAspectj.AspectjKeys.inputs
import com.typesafe.sbt.SbtAspectj._
import sbt.Keys._
import sbt._
object Build extends Build {
val appName = "Interceptor"
val appVersion = "1.0-SNAPSHOT"
val main = play.Project(appName, appVersion)
.settings(aspectjSettings: _*)
.settings(inputs in Aspectj <+= compiledClasses,
products in Compile <<= products in Aspectj,
products in Runtime <<= products in Compile)
}
自定义注释
package service;
/**
* @author z.benrhouma
* @since 09/09/2014
*/
public @interface STransaction {
}
交易方面:
package aspects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import play.db.jpa.JPA;
import play.libs.F;
/**
* @author z.benrhouma
* @since 29/03/2014
*/
@Aspect
public class TransactionAspect {
@Around("execution(* service.*.*(..)) && @annotation(service.STransaction)")
public Object logAccessRules(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
JPA.withTransaction(new F.Callback0() {
@Override
public void invoke() throws Throwable {
thisJoinPoint.proceed();
}
});
return null;
}
}
例如:
package service;
/**
* @author z.benrhouma
* @since 09/09/2014
*/
public class TransactionService {
@STransaction // --> this method will be wrapped with JPA.withTransaction
public static void doSomeProcessing(){
System.out.println("hello with transaction");
}
public static void doSomeProcessing2(){
System.out.println("hello without transaction");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.