You are on page 1of 24

Connecting to Database

Agenda

Problems with plain JDBC interaction Spring way of handling database access

Database Connectivity

Any non trivial enterprise application usually have a persistence mechanism and usually its a SQL compliant database. Spring does not provide any native support for database access. Spring provides integration to various data access framework which includes JDBC Hibernate iBatis Apache Object Relationship Bridge JPA Toplink

Database Connectivity

In spite of SQL standards there are variation in the dialect support by different vendors. Database resources need to be managed Executing and managing connections to database is a non trivial process. Developer has to manage transaction boundaries.

Database Connectivity
Curse of SQLException Unable to connect to database. Query being performed has syntax error. Tables/Columns do not exist Violates database constraint Cant do much about it.

Plain JDBC Way


Employee employee= new Employee(); employee.setName(Manmohan");
try{ Class.forName("org.hsqldb.jdbcDriver"); }catch(ClassNotFoundException cfe){ log.error("Driver not found"); } Connection conn = null; PreparedStatement stmt = null;

Plain JDBC Way


try {

conn = DriverManager.getConnection ("jdbc:hsqldb:hsql://localhost","sa","");


stmt = conn.prepareStatement ("insert into EMPLOYEE (name) values (?) "); stmt.setString(1, student.getName()); stmt.execute(); }catch(SQLException se){ log.error("Problem with data insert"); }

Plain JDBC Way


finally{ try{ if(stmt != null) { stmt.close(); } if(conn != null) { conn.close(); } }catch(SQLException se) { log.error(Could not close resource properly); }

Plain JDBC Way


1. 2. 3. 4. 5. 6. 7. Define connection parameters Open the connection Specify the statement Prepare and execute the statement Process any exception Handle transactions Close the connection We have not even talked about Transaction Details yet

Plain JDBC Way


1. 2. 3. 4. 5. 6. 7. 8. 9. Define connection parameters Open the connection Specify the statement Prepare and execute the statement Set up the loop to iterate through the results (if any) Do the work for each iteration Process any exception Handle transactions Close the connection

DAO

Spring promotes DAO pattern for data access. This promotes exposing functionality through interfaces

Service Object

DAO interface

DAO Implementation

DAO

Programming against DAO interface will shield us from implementation details of underlying data access code
public interface employeeDao{ public void saveEmployee(Employee employee); }

DAO

Move the implementation to save a student to EmployeeJdbcDao

public class EmployeeJdbcDao implements EmployeeDao{


public void saveEmployee(Employee employee) {

//Move all the JDBC ineraction code here


} }

Spring way to Connect Database


No matter which data access technology is used it has a fixed part and a programmer defined part. Spring handles the data access using templates and callbacks. The fixed part like opening closing connection is handled by template and the variable part like how to handle the result is handled by callbacks.

Spring way to Connect Database

Spring comes with several data access template for different persistence mechanism. Some of which are: JdbcTemplate SimpleJdbcTemplate HibernateTemplate JpaTemplate

JdbcTemplate

JdbcTemplate class simplifies working with JDBC It will automatically handle resource management, exception handling and transaction management It is a thread safe class so you can use a single instance that many classes can use. It also gives access to Connection with getConnection method

JdbcTemplate

Change the DAO implementation using JdbcTemplate

public class EmployeeJdbcDao implements EmployeeDao{ private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate template){ jdbcTemplate = tempalte; }

JdbcTemplate

Change the DAO implementation using JdbcTemplate

public void saveEmployee(Employee employee) { jdbcTemplate.update ("insert into Employee (name) values (?), employee.getName()); }

Where all code gone and who sets JdbcTemplate?

JdbcTemplate

Configure JdbcTemplate in configuration

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean>

JdbcTemplate

Configure dataSource

<bean id="dataSource" class="org.springframework.jdbc.datasource. DriverManagerDataSource> <property name="driverClassName" value="org.hsqldb.jdbcDriver" /> <property name="url value="jdbc:hsqldb:hsql://localhost" /> <property name="username" value="sa" /> <property name="password" value="" /> </bean>

JdbcTemplate Fetching results

Collection can be fetched and list of proper objects will get created

@Override public List<Employee> getEmployees() { return jdbcTemplate.query ("Select name as name, salary as salary from Employee", new ParameterizedRowMapper<Employee>(){ public Employee mapRow(ResultSet rs,int rowNum) throws SQLException { Employee employee = new Employee(); employee.setName(rs.getString("name")); employee.setSalary(rs.getInt("salary")); return employee;

Accessing Datasource

Accessing datasource using jndi lookup

<bean id =datasource class=org.springframework.jndi.JndiObjectFactoryBean> <property name=jndiName value=/jdbc/ds/> <property name=resourceRef value=true/> </bean>

Spring 2.0+ you can use jee namespace

<jee:jndi-lookup id=datasource jndi-name=jdbc/ds resource-ref=true />

Exception Handling

Handling of Exceptions is a pain as we have seen Spring Exceptions are unchecked so no need to catch them. Spring throws finer exception which gives better insight into problem The root of Spring exception hierarchy is DataAccessException

Conclusion

Problems with plain JDBC interaction Spring way of handling database access

You might also like