16.2. Connecting to a Database with the Spring Framework
Problem
You want to connect to a database using the Spring Framework. This gives you a nice way to add connection pooling and other capabilities to your SQL code.
Solution
Use the same Spring Framework configuration you’ve used in Java applications, but convert your Java source code to Scala. The biggest changes involve the differences in class casting between Java and Scala, and conversions between Java and Scala collections.
Discussion
To demonstrate this, create a basic Spring JDBC example. Start by creating a simple SBT project directory structure as demonstrated in Recipe 18.1.
Once the SBT directory structure is created, place this Spring applicationContext.xml file in the src/main/resources directory:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean
id=
"testDao"
class=
"springtests.TestDao"
>
<property
name=
"dataSource"
ref=
"basicDataSource"
/>
</bean>
<bean
id=
"basicDataSource"
class=
"org.apache.commons.dbcp.BasicDataSource"
>
<property
name=
"driverClassName"
value=
"com.mysql.jdbc.Driver"
/>
<property
name=
"url"
value=
"jdbc:mysql://localhost/mysql"
/>
<property
name=
"username"
value=
"root"
/>
<property
name=
"password"
value=
"root"
/>
<property
name=
"initialSize"
value=
"1"
/>
<property
name=
"maxActive"
value=
"5"
/>
</bean>
</beans>
This file declares that you’ll have a class named TestDao
in a package named springtests ...
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.