Java 使用Hibernate播放事务

Java 使用Hibernate播放事务,java,hibernate,jpa,playframework,Java,Hibernate,Jpa,Playframework,我正在使用带Hibernate的PlayVersion2.2。我正在尝试创建另一个“层”来管理数据库操作,我是否必须将每个事务都包装在这个层中,或者是否有其他更优雅的方法来完成,我必须采取变通办法来访问传递给方法的变量 JPA.withTransaction(new F.Callback0() { @Override public void invoke() throws Throwable { ... J

我正在使用带Hibernate的PlayVersion2.2。我正在尝试创建另一个“层”来管理数据库操作,我是否必须将每个事务都包装在这个层中,或者是否有其他更优雅的方法来完成,我必须采取变通办法来访问传递给方法的变量

    JPA.withTransaction(new F.Callback0() {

        @Override
        public void invoke() throws Throwable {
            ...
            JPA.em().persist(someObject);
            ...
        }
    });

使用注释

在本例中,我使用aspjectj包装带有自定义注释标记的方法,以应用JPA事务:

  • SBT版本=0.13.5
  • 播放版本=2.2.1
Plugins.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 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");
}
}

@事务性只能在操作方法中使用。您可以添加自定义批注处理器并包装事务性代码。
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");
}
}