Upload
barney
View
33
Download
2
Embed Size (px)
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
Citation preview
Connecting to Database
Problems with plain JDBC interaction Spring way of handling database access
Agenda
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
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
Can’t do much about it….
Database Connectivity
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. 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
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
Spring promotes DAO pattern for data access. This promotes exposing functionality through interfaces
DAO
Service Object DAO interface
DAO Implementation
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
}}
DAO
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:JdbcTemplateSimpleJdbcTemplateHibernateTemplateJpaTemplate
Spring way to Connect 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
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
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;
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