Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Controle de transação com SpringData, SpringJPA e Scala

Exemplo de controle de transação com SpringData e Scala

Implementação JDBC

package com.codesimples.jdbc

import com.typesafe.scalalogging.Logger
import org.springframework.transaction.support.{TransactionCallbackWithoutResult, TransactionTemplate}
import org.springframework.transaction.{PlatformTransactionManager, TransactionStatus}

trait JDBCTemplate {
  implicit val platformTransactionManager: PlatformTransactionManager
  implicit val logger: Logger

  def withTransaction( callback:  => Unit ) = {
    val transactionCallback: TransactionCallbackWithoutResult = transactionalCallback(callback)
    new TransactionTemplate(platformTransactionManager).execute(transactionCallback)
  }

  def transactionalCallback(callback: => Unit): TransactionCallbackWithoutResult = {
    new TransactionCallbackWithoutResult {
      override def doInTransactionWithoutResult(transactionStatus: TransactionStatus) = {
        try {
          callback
          transactionStatus.flush()
        } catch {
          case e: Exception => {
            transactionStatus.setRollbackOnly()
            logger.error("Transaction Error: ", e)
          }
        }
      }
    }
  }
}

Implementação JPA

package com.codesimples.jpa

import javax.persistence.EntityManager

import com.typesafe.scalalogging.Logger

trait JPATemplate {
  implicit val logger: Logger
  implicit val entityManager: EntityManager

  def withTransaction( callback:  => Unit ) = {
    val transaction = entityManager.getTransaction
    transaction.begin()
    try {
      callback
      transaction.commit()
    } catch {
      case e: Exception => {
        if(transaction.isActive) transaction.rollback()
        logger.error("Transaction Error: ", e)
      }
    }
  }
}

Uso

val user = Map[String,AnyRef](
  "id" -> UUID.randomUUID().toString,
  "persistenceType" -> "jdbc"
)
      
userPersistenceAdapter.withTransaction {
  userPersistenceAdapter.saveUser(user)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment