Transactor로 연결하기
데이터베이스 접근을 설정해 보세요.
Transactor로 연결하기은(는) CoddyKit의 무료 Scala for Backend Engineering & Functional Programming 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Scala for Backend Engineering & Functional Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Is a Transactor?
Doobie is a pure functional JDBC layer for Scala. A Transactor[F] is the bridge between Doobie's pure programs and a real database connection.
A Transactor knows how to acquire a JDBC Connection, run your program inside a transaction, and release resources safely.
It is parameterized by an effect type F[_] such as cats.effect.IO.
import doobie._
import cats.effect.IO
val xa: Transactor[IO] = ???The ConnectionIO Program
Doobie queries are values of type ConnectionIO[A]. They describe a computation that needs a JDBC connection but do not run yet.
You build these programs purely, then hand them to a Transactor to execute them. Nothing touches the database until you run it.
import doobie.implicits._
val program: ConnectionIO[Int] =
sql"select 42".query[Int].uniqueDriverManagerTransactor
The simplest Transactor is Transactor.fromDriverManager. It opens a brand new connection for every transaction using JDBC's DriverManager.
It needs the driver class name, JDBC URL, username, and password. It is fine for tests and scripts but has no connection pooling.
val xa = Transactor.fromDriverManager[IO](
driver = "org.postgresql.Driver",
url = "jdbc:postgresql://localhost:5432/app",
user = "postgres",
password = "secret",
logHandler = None
)Running a Program
To execute a ConnectionIO you call .transact(xa). This yields an F[A], here an IO[A].
The Transactor wraps the program in a transaction: it commits on success and rolls back on failure, releasing the connection either way.
import doobie.implicits._
val result: IO[Int] =
sql"select 42".query[Int].unique.transact(xa)Pooling with HikariCP
For production you want a connection pool. Doobie ships HikariTransactor, backed by HikariCP.
It is created as a Resource so the pool is shut down cleanly. You also pass an execution context for blocking JDBC operations.
import doobie.hikari.HikariTransactor
import cats.effect.IO
val xaRes: Resource[IO, HikariTransactor[IO]] =
HikariTransactor.newHikariTransactor[IO](
"org.postgresql.Driver",
"jdbc:postgresql://localhost/app",
"postgres", "secret",
connectEC
)Why a Resource?
A pooled Transactor owns long-lived state: open connections and background threads. Resource[F, A] guarantees acquisition and release are paired even on errors or cancellation.
You typically build the Transactor once at startup and reuse it for the whole application's lifetime.
xaRes.use { xa =>
program.transact(xa)
}The connectEC Pool
HikariCP needs an ExecutionContext to await connections from the pool. Doobie provides ExecutionContexts.fixedThreadPool for this, itself a Resource.
Keeping this separate from your compute pool prevents blocking connection acquisition from starving CPU-bound work.
import doobie.util.ExecutionContexts
val poolRes =
for {
ec <- ExecutionContexts.fixedThreadPool[IO](8)
xa <- HikariTransactor.newHikariTransactor[IO](
"org.postgresql.Driver", url, user, pass, ec)
} yield xaConfiguring an Existing DataSource
If you already have a configured javax.sql.DataSource (e.g. a tuned Hikari instance), wrap it directly with Transactor.fromDataSource.
This is common when a framework manages the pool and you only want Doobie to use it.
val xa = Transactor.fromDataSource[IO](
dataSource = myDataSource,
connectEC = connectEC
)Smoke-Testing the Connection
A simple health check is to run select 1 through the Transactor. If it returns, your driver, URL, and credentials are all working.
This is a good first step before wiring up real queries.
val check: IO[Int] =
sql"select 1".query[Int].unique.transact(xa)
// check.unsafeRunSync() == 1Transactor Internals: Strategy
A Transactor is built from interpreters and a Strategy. The Strategy controls what happens around each transaction: before, after, oops (on error), and always.
The default strategy sets auto-commit off, commits after success, rolls back on error, and always closes the connection.
import doobie.util.transactor.Strategy
val noCommit = xa.copy(
strategy0 = Strategy.default.copy(after = doobie.free.connection.unit)
)Logging and Observability
Doobie can log every statement, its arguments, and timing. Modern versions attach a LogHandler[F] per query rather than per Transactor.
This is invaluable for spotting slow queries and verifying parameter binding in production.
import doobie.util.log._
val handler: LogHandler[IO] = (ev: LogEvent) =>
IO.println(ev.sql)Quick Check
Test your understanding of Transactors.
Recap
A Transactor[F] connects pure ConnectionIO programs to a real database. fromDriverManager suits tests; HikariTransactor and fromDataSource suit production via pooling.
Build pooled Transactors as a Resource, run programs with .transact(xa), and let the default Strategy handle commit, rollback, and cleanup.
자주 묻는 질문
“Transactor로 연결하기” 강의는 무료인가요?
네 — “Transactor로 연결하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Scala for Backend Engineering & Functional Programming 강의 전체를 잠금 해제할 수 있습니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“Transactor로 연결하기”에서 뭘 배우나요?
데이터베이스 접근을 설정해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Scala for Backend Engineering & Functional Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Scala for Backend Engineering & Functional Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Scala for Backend Engineering & Functional Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“Transactor로 연결하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Scala for Backend Engineering & Functional Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Scala for Backend Engineering & Functional Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.