Introduction

With Scala, you can interact with traditional relational databases using their JDBC drivers, just like you do in Java. As an example of this, the first recipe in this chapter demonstrates how to connect to a MySQL database using the “plain old JDBC” approach.

In the real world, once applications grow in size, few people use plain old JDBC to work with databases. Typically on those projects you use a library, such as the Spring Framework, to make development easier and handle issues like connection pooling. Therefore, this chapter also demonstrates the few changes you’ll need to make to use the Spring JDBC library with Scala. As an added benefit, by showing the changes needed to instantiate a bean from a Spring application context file, this recipe will help you use other Spring libraries with Scala as well. You can use other technologies with Scala, such as the Java Persistence API (JPA) and Hibernate, with just a few changes.

The Scala community is also developing new approaches to database development. The Squeryl and Slick libraries both take “type-safe” approaches to writing database code. The Squeryl documentation states that it’s a “Scala ORM and DSL.” In a manner similar to Hibernate, Squeryl lets you write database code like this:

// insert
val bill = people.insert(new Person("Bill"))
val candy = people.insert(new Person("Candy"))

// update
stock.price = 500.00
stocks.update(stock)

With Squeryl’s DSL, you can also write statements like this:

update(stocks)(s => where(s.symbol ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.