SpringBoot+JPA(Hibernate)事物手动控制

在启动类中将Session交由Spring托管
@Bean
def hibernateSessionFactory() : HibernateJpaSessionFactoryBean = {
  new HibernateJpaSessionFactoryBean
} 
在需要事物手动控制的class中注入SessionFactory和EntityManager
 
  
@Autowired
var sessionFactory: SessionFactory = _

@Autowired
var entityManager: EntityManager = _
定义事物方法
 
  
private def transactional(payload: (Session => Unit)): Unit = {
  val session = sessionFactory.openSession()
  val tx = session.beginTransaction()
  try {
    payload(session)
    session.flush()
    session.clear()
    tx.commit()
  } catch {
    case t: Throwable =>
      val stat = tx.getStatus
      if (stat.isNotOneOf(TransactionStatus.COMMITTED, TransactionStatus.ROLLED_BACK) && stat.isOneOf(TransactionStatus.ACTIVE)) {
        try {
          tx.rollback()
          throw t
        } finally {}
      }
  } finally {
    session.close()
  }
}
使用方法,传入一个方法,该方法的参数是一个session,无返回值
 
  
def qjhRepaymentDataInitializing(): Unit = {
  var initialSql = "sql语句"
  if (response.code == Consts.MSG_SUCCESS._1) {
    var dataStr = JSON.toJSON(response.data).toString
    var dataList: util.List[QjhRepaymentPlan] = JSON.parseArray(dataStr, classOf[QjhRepaymentPlan])
    import scala.collection.JavaConversions._
      /**
	*下面就是使用,类似于lambda表达式,这里是scala的语法糖
	*/
    transactional(session => {
      for (p <- dataList) {
        var repayment = new OrderRepayment
        repayment.id = Consts.PRODUCT_QJH_ID_PREFIX + p.id
        repayment.order_Id = Consts.PRODUCT_QJH_ID_PREFIX + p.portfolioId
        repayment.amount = -p.principal
        repayment.qdwId = p.qdwId
        repayment.repaidTime = p.repaidTime
        repayment.productKey = Consts.PRODUCT_KEY_QJH
        session.save(repayment)
      }
    })
  }

你可能感兴趣的:(Java后台)