ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Magnum 기본 사용
    scala jdbc/magnum 2024. 11. 7. 22:20

    https://github.com/AugustNagro/magnum 을 사용해 본다.

     

     

    build.sbt

    libraryDependencies += "com.augustnagro" %% "magnum" % "1.3.0"
    libraryDependencies += "com.zaxxer" % "HikariCP" % "5.0.1"
    libraryDependencies += "mysql" % "mysql-connector-java" % "8.0.33"

     

     

    코드

    import com.augustnagro.magnum.*
    import com.mysql.cj.jdbc.MysqlDataSource
    import com.zaxxer.hikari.pool.HikariPool
    import com.zaxxer.hikari.{HikariConfig, HikariDataSource}
    
    import javax.sql.DataSource
    import scala.concurrent.duration.MINUTES
    
    object MagnumTest {
      @Table(MySqlDbType, SqlNameMapper.CamelToSnakeCase)
      case class Person(name: String, age: Int)
    
      def main(args: Array[String]): Unit = {
        val mysqlDataSource: MysqlDataSource = new MysqlDataSource()
        mysqlDataSource.setUrl(
          "jdbc:mysql://localhost:3306/test"
        )
        mysqlDataSource.setUser("admin")
        mysqlDataSource.setPassword("admin123")
        mysqlDataSource.setAutoReconnect(true)
    
        val hikariConfig: HikariConfig = new HikariConfig()
        hikariConfig.setDataSource(mysqlDataSource)
        hikariConfig.setMaximumPoolSize(40)
        hikariConfig.setConnectionTimeout(MINUTES.toMillis(1))
        hikariConfig.setMaxLifetime(MINUTES.toMillis(60))
    
    //    val pool: HikariPool = new HikariPool(hikariConfig)
        val dataSource: DataSource = new HikariDataSource(hikariConfig)
        val xa: Transactor = Transactor(dataSource)
    
    //    val xa: Transactor = Transactor(
    //      dataSource,
    //      sqlLogger = SqlLogger.logSlowQueries(500.milliseconds),
    //      connectionConfig = con =>
    //        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ)
    //    )
    
        val people: Seq[Person] = connect(xa) {
          sql"select * from person".query[Person].run()
        }
    
        // transaction 처리시
        val people2: Seq[Person] = transact(xa) {
          sql"select * from person".query[Person].run()
        }
    
        val people3: Seq[Person] = connect(xa) {
          val nameOpt = Some("A")
          sql"select * from person where name=$nameOpt".query[Person].run()
        }
    
        // dynamic query
        val people4: Seq[Person] = connect(xa) {
    //      val nameOpt: Option[String] = Some("A")
          val nameOpt: Option[String] = None
    
          val cond: Frag = Spec[Person]
            .where(nameOpt.map(n => sql"name=$n").getOrElse(sql""))
            .build
    
          val frag: Frag = Frag(
            s"select * from person ${cond.sqlString}",
            cond.params,
            cond.writer
          )
    
          frag.query[Person].run()
        }
    
        people4.foreach { p =>
          println(s"${p.name} ${p.age}")
        }
      }
    }

    댓글

Designed by Tistory.