connecting to database

24
Connecting to Database

Upload: barney

Post on 09-Jan-2016

40 views

Category:

Documents


2 download

DESCRIPTION

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 it’s a SQL compliant database. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Connecting to Database

Connecting to Database

Page 2: Connecting to Database

Problems with plain JDBC interaction Spring way of handling database access

Agenda

Page 3: Connecting to Database

Any non trivial enterprise application usually have a persistence mechanism and usually it’s 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

Page 4: Connecting to Database

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

Page 5: Connecting to Database

Curse of SQLException Unable to connect to database. Query being performed has syntax error. Tables/Columns do not exist Violates database constraint

Can’t do much about it….

Database Connectivity

Page 6: Connecting to Database

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

Page 7: Connecting to Database

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

Page 8: Connecting to Database

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

Page 9: Connecting to Database

1. Define connection parameters2. Open the connection3. Specify the statement4. Prepare and execute the statement5. Process any exception6. Handle transactions7. Close the connection

We have not even talked about Transaction Details yet

Plain JDBC Way

Page 10: Connecting to Database

1. Define connection parameters2. Open the connection3. Specify the statement4. Prepare and execute the statement5. Set up the loop to iterate through the results (if any)6. Do the work for each iteration7. Process any exception8. Handle transactions9. Close the connection

Plain JDBC Way

Page 11: Connecting to Database

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

DAO

Service Object DAO interface

DAO Implementation

Page 12: Connecting to Database

Programming against DAO interface will shield us from implementation details of underlying data access code

public interface employeeDao{ public void saveEmployee(Employee

employee); }

DAO

Page 13: Connecting to Database

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

}}

DAO

Page 14: Connecting to 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

Page 15: Connecting to Database

Spring comes with several data access template for different persistence mechanism. Some of which are:JdbcTemplateSimpleJdbcTemplateHibernateTemplateJpaTemplate

Spring way to Connect Database

Page 16: Connecting to Database

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

Page 17: Connecting to Database

Change the DAO implementation using JdbcTemplate

public class EmployeeJdbcDao implements EmployeeDao{

private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate template){

jdbcTemplate = tempalte; }

JdbcTemplate

Page 18: Connecting to Database

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

Page 19: Connecting to Database

Configure JdbcTemplate in configuration

<bean id="jdbcTemplate"

class="org.springframework.jdbc.core.JdbcTemplate">

<property name="dataSource" ref="dataSource" /></bean>

JdbcTemplate

Page 20: Connecting to Database

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

Page 21: Connecting to Database

JdbcTemplate – Fetching results

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

@Overridepublic 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;

Page 22: Connecting to Database

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” />

Page 23: Connecting to Database

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

Page 24: Connecting to Database

Conclusion

Problems with plain JDBC interaction Spring way of handling database access