2014-09-05 60 views
0

我使用Hibernate的Play 2.2版本。我正在嘗試創建另一個用於管理數據庫操作的「層」,我是否必須將每個事務都包含在這個中,還是有其他一些更優雅的方法來做到這一點,我必須做出變通方法來訪問傳遞給方法的變量。使用Hibernate播放事務

JPA.withTransaction(new F.Callback0() { 

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

回答

0

使用註釋@Transactional

+0

@Transactional只能在操作方法中。 – 2014-09-05 11:31:34

+0

您可以添加自定義註釋處理器幷包裝事務代碼。 – 2014-09-05 16:19:50

0

在這個例子中,我使用aspjectj包裝標有一個自定義的註釋方法適用JPA交易:github example

  • 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 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"); 
} 
}