spring jdbcspring jdbc part 1 - core...

28
© 2008 coreservlets.com Spring JDBC Spring JDBC Part 1 Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/spring.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. © 2008 coreservlets.com For live Spring & Hibernate training, see t htt // lt / courses at http://courses.coreservlets.com/. Taught by the experts that brought you this tutorial. Available at public venues or customized versions Available at public venues, or customized versions can be held on-site at your organization. C d l d dt ht b M t H ll Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Courses developed and taught by Marty Hall Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics Courses developed and taught by coreservlets.com experts (edited by Marty) Spring, Hibernate/JPA, EJB3, Ruby/Rails Contact [email protected] for details

Upload: others

Post on 06-Aug-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

© 2008 coreservlets.com

Spring JDBCSpring JDBCPart 1

Originals of Slides and Source Code for Examples:http://courses.coreservlets.com/Course-Materials/spring.html

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2008 coreservlets.com

For live Spring & Hibernate training, see t htt // l t /courses at http://courses.coreservlets.com/.

Taught by the experts that brought you this tutorial. Available at public venues or customized versionsAvailable at public venues, or customized versions

can be held on-site at your organization.

C d l d d t ht b M t H ll

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

• Courses developed and taught by Marty Hall– Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics

• Courses developed and taught by coreservlets.com experts (edited by Marty)– Spring, Hibernate/JPA, EJB3, Ruby/Rails

Contact [email protected] for details

Page 2: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Topics in This Sectionp

• Introduction to Spring JDBC • Spring JDBC development• Spring IoC integration

Java EE training: http://courses.coreservlets.com

© 2008 coreservlets.com

Introduction

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

Page 3: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Motivationpublic void save(Customer customer) {

Connection conn = null;boolean autoCommit = false;try{

hi d i ()

private boolean update(Customer customer, Connection conn) {

PreparedStatement stmt = null;try{

stmt conn prepareStatement(

private boolean insert(Customer customer, Connection conn) {

PreparedStatement stmt = null;try{

stmt conn prepareStatement(conn = this.dataSource.getConnection();autoCommit = conn.getAutoCommit();conn.setAutoCommit(false);if(!update(customer, conn)){

insert(customer, conn);}conn.commit();

}catch(SQLException e){

stmt = conn.prepareStatement("update customer set name = ? where id = ?");

stmt.setString(1, customer.getName());stmt.setString(2, customer.getId());return stmt.executeUpdate() > 0;

}catch(SQLException e){

throw new CustomerPersistenceException("Error: SQL."

il d d )

stmt = conn.prepareStatement("insert into customer (id, name) values (?,

?)");stmt.setString(1, customer.getId());stmt.setString(2, customer.getName());return stmt.executeUpdate() > 0;

}catch(SQLException e){

throw new CustomerPersistenceException("Error: SQL "

if(conn != null){try{

conn.rollback();}catch(SQLException suppressed){}

}throw new CustomerPersistenceException("Error: SQL."+ " Error saving customer: " + customer,e);

+ " Failed to update customer.",e);}finally{

if(stmt != null){try{

stmt.close();stmt = null;

}catch(Exception suppressed){}

SQL."+ " Failed to insert customer.",e);

}finally{

if(stmt != null){try{

stmt.close();stmt = null;

}

}catch(RuntimeException e){

if(conn != null){try{

conn.rollback();}catch(SQLException suppressed){}

}throw new CustomerPersistenceException("Error:

}}

}

catch(Exception suppressed){}}

}}

throw new CustomerPersistenceException( Error: SQL."+ " Error saving customer: " + customer,e);

}finally{

if(conn != null){try{

conn.setAutoCommit(autoCommit);conn.close();conn = null;

Java EE training: http://courses.coreservlets.com

conn = null;}catch(SQLException suppressed){}

}}

}

Spring JDBC Solutionp g

public void save(Customer customer) {Map<String, Object> parameterMap =Map<String, Object> parameterMap new HashMap<String, Object>();

parameterMap.put("customerId", customer.getId());parameterMap.put("customerName", customer.getName());

boolean updated = simpleJdbc.update("update customer set name = :customerName"+ " where id = :customerId" parameters) > 0;+ where id = :customerId , parameters) > 0;

if(updated){return;

}

simpleJdbc.update("i t i t t (id )"

Java EE training: http://courses.coreservlets.com

"insert into customer (id, name)"+ " values (:customerId, :customerName)", parameters);

}

Page 4: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Spring JDBCp g

• Standalone JDBC softwareN d d i i S i I C t i– No dependencies on a running Spring IoC container

• Templated software– Replaces tedious Java SQL APIs

i i C i i k– Mitigates JDBC resource mismanagement risks

• No configuration management overhead– No XML – No annotations

• Pure code solution– Explicit settings– Verbose– No class or domain modeling constraints

• Interface-driven domain models

Java EE training: http://courses.coreservlets.com

• Complex constructors• Separates class and relational cardinality

• Outperforms O/R mapping solutions

Spring JDBC Templatesp g p

• Fine-grained templates– JdbcTemplate– NamedParameterJdbcTemplate

• Coarse grained templates• Coarse-grained templates– SimpleJdbcTemplate– SimpleJdbcInsertp– SimpleJdbcCall

• SQL objects– SqlUpdate– MappingSqlQuery

Java EE training: http://courses.coreservlets.com

Page 5: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

© 2008 coreservlets.com

S i I C PSpring IoC Process ReviewReview

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

Spring IoC Processp g

• Develop POJO libraryD fi th i t f– Define the interfaces

– Create the implementations

• Register Spring JARsi j– spring-core.jar

– spring-context.jar– spring-beans.jar

l i j– commons-logging.jar

• Create the bean definitions file– Default to the file name applicationContext.xml– Place the file in an accessible location

• Register beans– Register the spring-beans XML schema into the bean definitions file

Java EE training: http://courses.coreservlets.com

Assign bean identifiers using the id attribute– Specify the bean creation method; e.g, the class attribute for direct

constructor invocation

Page 6: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Spring IoC Process Continuedp g

• Integrate configurationRegister the s i c t t XML schema into the bean definitions– Register the spring-context XML schema into the bean definitions file

– Declare a property-placeholder element with the configuration file path assigned to the location attributepath assigned to the location attribute

• Define bean interdependencies– Select a DI method; e.g., constructor, property setter, lookup-method, etc…– Specify the injection value; e g collaborators values resources etc– Specify the injection value; e.g., collaborators, values, resources, etc…

• Initialize container– Select an ApplicationContext implementation

• The integration method will depend on the target environment• The integration method will depend on the target environment

– Specify the location of the bean definitions file(s)

• Access and use beans from the Spring IoC containerFor example via the BeanFactory API

Java EE training: http://courses.coreservlets.com

– For example, via the BeanFactory API• BeanFactory#getBean(beanName:String):Object• BeanFactory#getBean(beanName:String, requiredType:Class):Object

Develop POJO Libraryp y

package coreservlets;

public class Customer {

private String id; private String name;

public Customer(String id, String name){this id = id;this.id = id;this.name = name;

}public String getId() {return id;

}public String getName() {

t

Java EE training: http://courses.coreservlets.com

return name;}

}

Page 7: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Develop POJO Libraryp y

public interface CustomerQuery {

public Customer getCustomerByName(String name);

}

Java EE training: http://courses.coreservlets.com

Develop POJO Libraryp y

public class CustomerQueryImpl implements CustomerQuery {

private List<Customer> customers;

public CustomerQueryImpl(List<Customer>customers) {this.customers = customers;

}

public Customer getCustomerByName(String name) {public Customer getCustomerByName(String name) {for(Customer c : customers){if(c.getName().equals(name)){return c;

}}return null;

}

Java EE training: http://courses.coreservlets.com

}}

Page 8: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Register Spring JARsg p g

Java EE training: http://courses.coreservlets.com

Register Spring JARsEclipse classpathEclipse .classpath

<?xml version="1.0" encoding="UTF-8"?><classpath><classpath><classpathentry kind="src" path="src"/><classpathentry kind="lib" path="lib/spring-core.jar" /><classpathentry kind="lib" path="lib/spring-beans.jar" /><classpathentry kind="lib" path="lib/spring-context.jar" /><classpathentry kind="lib" path="lib/commons-logging.jar"/><classpathentry kind="con"path="org eclipse jdt launching JRE CONTAINER"/>path= org.eclipse.jdt.launching.JRE_CONTAINER />

<classpathentry kind="output" path=".eclipseclasses"/></classpath>

Java EE training: http://courses.coreservlets.com

Page 9: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Create the bean definitions file

• Default to applicationContext.xml• Place the file in an accessible location

– Classpath, filesystem or web module path

Java EE training: http://courses.coreservlets.com

Register Beans

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"<beans xmlns http://www.springframework.org/schema/beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

</beans>

Java EE training: http://courses.coreservlets.com

Page 10: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Register Beans

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"<beans xmlns http://www.springframework.org/schema/beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="customerQuery"class="coreservlets.mockup.CustomerQueryImpl" />

</beans>

Java EE training: http://courses.coreservlets.com

Define Bean Interdependencies

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"<beans xmlns http://www.springframework.org/schema/beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="customerQuery"class="coreservlets.mockup.CustomerQueryImpl">

<constructor-arg><constructor-arg><list><bean class="coreservlets.Customer"><property name="id" value="jjoe" /><property name="name" value="Java Joe" />

</bean></list>/ t t

Java EE training: http://courses.coreservlets.com

</constructor-arg></bean>

</beans>

Page 11: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Initialize Container

import org.springframework.context.support.*;

public class Main {

public static void main(String[]args) {

BeanFactory beanFactory = new ClassPathXmlApplicationContext("/applicationContext.xml");

} }}

Java EE training: http://courses.coreservlets.com

Access and Use Beans

import org.springframework.context.support.*;public class Main {public class Main { public static void main(String[]args) {

BeanFactory beanFactory = new ClassPathXmlApplicationContext("/applicationContext.xml");

CustomerQuery query = (CustomerQuery) beanFactory.getBean("customerQuery");

C t tCustomer customer =query.getCustomerByName("Java Joe");

System out println(customer);

Java EE training: http://courses.coreservlets.com

System.out.println(customer);}

}

Standard output

Customer id=jjoe, name=Java Joe

Page 12: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

© 2008 coreservlets.com

S i JDBCSpring JDBC ProcessProcess

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

Spring JDBC Processp g

• Define persistence interfaces• Register Spring JDBC JARs

– Compilation dependencies• spring-jdbc jarspring jdbc.jar• spring-tx.jar

– Runtime dependencies• spring core jar• spring-core.jar• spring-context.jar• spring-beans.jar• commons-logging jar• commons-logging.jar

Java EE training: http://courses.coreservlets.com

Page 13: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Spring JDBC Process ContinuedContinued

• Create persistence implementations – Defer connectivity responsibilities

• Design class for DataSource dependency injection– Use Spring JDBC APIsp g

• Initialize Spring JDBC template(s) with the injected DataSource

• Initialize and execute the persistence objects• Initialize and execute the persistence objects– Instantiate the persistence objects

• Inject a DataSource object for connectivity

Java EE training: http://courses.coreservlets.com

Develop Persistence Interfacesp

public interface CustomerQuery {

public Customer getCustomerByName(String name);

}

Java EE training: http://courses.coreservlets.com

Page 14: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Develop Persistence Interfacesp

package coreservlets;

public class Customer {

private String id;

private String name;

public Customer(String id String name){public Customer(String id, String name){this.id = id;this.name = name;

}public String getId() {return id;

}bli St i tN () {

Java EE training: http://courses.coreservlets.com

public String getName() {return name;

}}

Register Spring JDBC JARsg p g

Java EE training: http://courses.coreservlets.com

Page 15: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Register Spring JDBC JARsEclipse classpathEclipse .classpath

<?xml version="1.0" encoding="UTF-8"?><classpath><classpath><classpathentry kind="src" path="src"/> <classpathentry kind="lib" path="lib/spring-core.jar" /><classpathentry kind="lib" path="lib/spring-beans.jar" /> l h ki d lib h lib/ i jdb j /<classpathentry kind="lib" path="lib/spring-jdbc.jar" />

<classpathentry kind="lib" path="lib/spring-tx.jar" /> <classpathentry kind="lib" path="lib/commons-logging.jar"/>

<classpathentry kind="con"<classpathentry kind conpath="org.eclipse.jdt.launching.JRE_CONTAINER"/>

<classpathentry kind="output" path=".eclipseclasses"/></classpath>

Java EE training: http://courses.coreservlets.com

Implement Persistence Classp

import java.sql.ResultSet;import java.sql.SQLException;import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.dao.*;import org.springframework.jdbc.core.simple.*;

public class SpringJdbcCustomerQuerypublic class SpringJdbcCustomerQueryimplements CustomerQuery {

private SimpleJdbcTemplate jdbc;

public SpringJdbcCustomerQuery(DataSource dataSource) {this.jdbc = new SimpleJdbcTemplate(dataSource);

}

Java EE training: http://courses.coreservlets.com

}...

}

Page 16: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Implement Persistence Class ContinuedContinued

public class SpringJdbcCustomerQueryimplements CustomerQuery {implements CustomerQuery {...public Customer getCustomerByName(String customerName) {try{return this.jdbc.queryForObject("select id, name from customer where name = ?", customerRowMappercustomerName);, customerName);

}catch(EmptyResultDataAccessException e){return null;

}}...

}

Java EE training: http://courses.coreservlets.com

}

Initialize and Execute Persistence ObjectsPersistence Objects

public class Main {public static void main(String[] args) throws Exception {public static void main(String[] args) throws Exception {DataSource dataSource =new EmbeddedDerbyDataSource("target/ngcdb", "/setup.sql");

CustomerQuery query = new SpringJdbcCustomerQuery(dataSource);

Customer customer = query getCustomerByName("Java Joe");query.getCustomerByName( Java Joe );

System.out.println(customer); }

}

Java EE training: http://courses.coreservlets.com

Standard output

Customer id=jjoe, name=Java Joe

Page 17: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

© 2008 coreservlets.com

S i JDBC dSpring JDBC and Spring IoC ProcessSpring IoC Process

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

Spring JDBC and Spring IoC ProcessProcess

• Register Spring JARsi j– spring-core.jar

– spring-context.jar– spring-beans.jar

spring jdbc jar– spring-jdbc.jar– spring-tx.jar– commons-logging.jar

• Develop persistence interfaces• Develop persistence interfaces• Create the persistence implementations

– Defer connectivity responsibilities• Design class for DataSource dependency injection

– Use Spring JDBC APIs• Initialize Spring JDBC template(s) with the injected DataSource

Java EE training: http://courses.coreservlets.com

• Create the bean definitions file– Default to the file name applicationContext.xml– Place the file in an accessible location

Page 18: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Spring JDBC and Spring IoC Process ContinuedProcess Continued

• Register beansR i t th i b XML h i t th b d fi iti fil– Register the spring-beans XML schema into the bean definitions file Assign bean identifiers using the id attribute

• Register a DataSource bean• Register persistence implementation beans

– Specify the bean creation method; e.g, the class attribute for direct constructor invocation

• Integrate configuration– Register the spring-context XML schema into the bean definitions

file– Declare a property-placeholder element with the configuration file

th i d t th l ti tt ib tpath assigned to the location attribute• Map DataSource configuration into DataSource

• Define bean interdependenciesS l t DI th d t t t tt l k th d t

Java EE training: http://courses.coreservlets.com

– Select a DI method; e.g., constructor, property setter, lookup-method, etc…– Specify the injection value; e.g., collaborators, values, resources, etc…

• Register the DataSource with persistence implementations

Spring JDBC and Spring IoC Process ContinuedProcess Continued

• Initialize containerS l t A li ti C t t i l t ti– Select an ApplicationContext implementation

• The integration method will depend on the target environment

– Specify the location of the bean definitions file(s)

• Access and use beans from the Spring IoC container• Access and use beans from the Spring IoC container– For example, via the BeanFactory API

• BeanFactory#getBean(beanName:String):Object• BeanFactory#getBean(beanName:String, requiredType:Class):Object

Java EE training: http://courses.coreservlets.com

Page 19: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Develop Persistence Interfacesp

public interface CustomerQuery {

public Customer getCustomerByName(String name);

}

Java EE training: http://courses.coreservlets.com

Develop Persistence Interfacesp

package coreservlets;

public class Customer {

private String id;

private String name;

public Customer(String id String name){public Customer(String id, String name){this.id = id;this.name = name;

}public String getId() {return id;

}bli St i tN () {

Java EE training: http://courses.coreservlets.com

public String getName() {return name;

}}

Page 20: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Register Spring JDBC JARsg p g

Java EE training: http://courses.coreservlets.com

Register Spring JDBC JARsEclipse classpathEclipse .classpath

<?xml version="1.0" encoding="UTF-8"?><classpath><classpath><classpathentry kind="src" path="src"/><classpathentry kind="lib" path="lib/spring-core.jar" /><classpathentry kind="lib" path="lib/spring-beans.jar" /> <classpathentry kind="lib" path="lib/spring-context.jar" /><classpathentry kind="lib" path="lib/spring-jdbc.jar" /> <classpathentry kind="lib" path="lib/spring-tx.jar" /> <classpathentry kind="lib" path="lib/commons-logging jar"/><classpathentry kind= lib path= lib/commons-logging.jar /><classpathentry kind="con"path="org.eclipse.jdt.launching.JRE_CONTAINER"/>

<classpathentry kind="output" path=".eclipseclasses"/></classpath>

Java EE training: http://courses.coreservlets.com

Page 21: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Implement Persistence Classp

import java.sql.ResultSet;import java.sql.SQLException;import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.dao.*;import org.springframework.jdbc.core.simple.*;

public class SpringJdbcCustomerQuerypublic class SpringJdbcCustomerQueryimplements CustomerQuery {

private SimpleJdbcTemplate jdbc;

public SpringJdbcCustomerQuery(DataSource dataSource) {jdbc = new SimpleJdbcTemplate(dataSource);

}

Java EE training: http://courses.coreservlets.com

}...

}

Implement Persistence Class ContinuedContinued

public class SpringJdbcCustomerQueryimplements CustomerQuery {implements CustomerQuery {...private ParameterizedRowMapper<Customer> customerRowMapper =new ParameterizedRowMapper<Customer>(){public Customer mapRow(ResultSet rslt, int rowNum)

throws SQLException {return new Customer(rslt.getString("id"),

rslt getString("name"));rslt.getString( name ));}

}; ...

}

Java EE training: http://courses.coreservlets.com

Page 22: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Implement Persistence Class ContinuedContinued

public class SpringJdbcCustomerQueryimplements CustomerQuery {implements CustomerQuery {...public Customer getCustomerByName(String customerName) {try{return jdbc.queryForObject("select id, name from customer where name = ?", customerRowMappercustomerName);, customerName);

}catch(EmptyResultDataAccessException e){return null;

}}...

}

Java EE training: http://courses.coreservlets.com

}

Create the bean definitions file

• Default to applicationContext.xml• Place the file in an accessible location

– Classpath, filesystem or web module path

Java EE training: http://courses.coreservlets.com

Page 23: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Register Beans

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"<beans xmlns http://www.springframework.org/schema/beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

</beans>

Java EE training: http://courses.coreservlets.com

Register Beans

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"<beans xmlns http://www.springframework.org/schema/beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="customerQuery"class="coreservlets.SpringJdbcCustomerQuery" />

<bean id="dataSource"class="coreservlets.util.EmbeddedDerbyDataSource" />

</beans>

Java EE training: http://courses.coreservlets.com

Page 24: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Integrate Configurationg g

• Create the properties file– dataSource.properties

• Place the file in an accessible locationl th t– classpath root

Java EE training: http://courses.coreservlets.com

Integrate Configurationg g

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"<beans xmlns http://www.springframework.org/schema/beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd">

<bean id="customerQuery"class="coreservlets.SpringJdbcCustomerQuery" />

<bean id="dataSource"class="coreservlets.util.EmbeddedDerbyDataSource" />

/b

Java EE training: http://courses.coreservlets.com

</beans>

Page 25: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Integrate Configurationg g

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"<beans xmlns http://www.springframework.org/schema/beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:property-placeholder location="classpath:/dataSource.properties" />

<bean id="customerQuery"class="coreservlets.SpringJdbcCustomerQuery" />

b id "d t S "

Java EE training: http://courses.coreservlets.com

<bean id="dataSource"class="coreservlets.util.EmbeddedDerbyDataSource" />

</beans>

Define Bean Interdependencies

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"<beans xmlns http://www.springframework.org/schema/beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="customerQuery" class="coreservlets.SpringJdbcCustomerQuery"><constructor-arg ref="dataSource" />

</bean></bean>

<bean id="dataSource" class="coreservlets.util.EmbeddedDerbyDataSource"><constructor-arg value="${derby.db.name}" /><constructor-arg><list><value>${derby.db.setup}</value>/li t

Java EE training: http://courses.coreservlets.com

</list></constructor-arg>

</bean> </beans>

Page 26: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Initialize Container

import org.springframework.context.support.*;

public class Main {

public static void main(String[]args) {

BeanFactory beanFactory = new ClassPathXmlApplicationContext("/applicationContext.xml");

} }}

Java EE training: http://courses.coreservlets.com

Access and Use Beans

import org.springframework.context.support.*;public class Main {public class Main { public static void main(String[]args) {

BeanFactory beanFactory = new ClassPathXmlApplicationContext("/applicationContext.xml");

CustomerQuery query = (CustomerQuery) beanFactory.getBean("customerQuery");

C t tCustomer customer =query.getCustomerByName("Java Joe");

System out println(customer);

Java EE training: http://courses.coreservlets.com

System.out.println(customer);}

}

Standard output

Customer id=jjoe, name=Java Joe

Page 27: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

© 2008 coreservlets.com

WWrap-up

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.

Spring JDBC and Spring IoC ProcessProcess

• Spring JARs i jdb j i t j i j i– spring-jdbc.jar, spring-tx.jar, spring-core.jar, spring-

context.jar, spring-beans.jar, commons-logging.jar• Develop persistence implementations

– Initialize JDBC template(s) with a DataSource– Defer connectivity responsibilities. Use constructor or property setter DI

integrating with the DataSource

C• Create applicationContext.xml– Save in an accessible location

• Register and wire beansg– Register spring-beans XML schema– Create persistence and DataSource beans– Wire DataSource bean into persistence beans using constructor or

Java EE training: http://courses.coreservlets.com

property setter DI

Page 28: Spring JDBCSpring JDBC Part 1 - Core Servletscourses.coreservlets.com/Course-Materials/pdf/spring/05-spring-jdbc1.pdfSpring JDBC Process Continued • Create persistence implementations

Spring JDBC and Spring IoC Process ContinuedProcess Continued

• Integrate configurationC t d th ti fil i ibl l ti– Create and save the properties file in an accessible location

– Register spring-context XML schema– Create a property-placeholder declaration with a location

attributeattribute

• Initialize container– Instantiate a BeanFactory

• e g ClassPathXmlApplicationContext• e.g., ClassPathXmlApplicationContext

• Access and use beans from the Spring IoC container– Pass the bean name to BeanFactory#getBean(beanName:String):ObjectBeanFactory#getBean(beanName:String):Object

Java EE training: http://courses.coreservlets.com

© 2008 coreservlets.com

Q ti ?Questions?

Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

Developed and taught by well-known author and developer. At public venues or onsite at your location.