Spring framework part 2

59
Spring Framework Part 2 By Haroon Idrees

description

spring framework integration, Sprin JDBC, hibernate my batis and transection

Transcript of Spring framework part 2

Page 1: Spring framework part 2

Spring Framework Part 2

By Haroon Idrees

Page 2: Spring framework part 2

Recap

Spring-JDBC

Spring-ORM

Spring-Transactions

Agenda

Page 3: Spring framework part 2

Recap

Page 4: Spring framework part 2

Architecture & Modules

Dependency Injection & IOC

Spring configuration

Example

Recap

Page 5: Spring framework part 2

Architecture & Modules

Page 6: Spring framework part 2

Architecture & Modules

Page 7: Spring framework part 2

IoC and DI features based onthe BeanFactory containerconcept

Powerful languagefor querying andmanipulating anobject graph atruntime

Build on the base of Beans and Core. Provide way to access objects, support for i18n, resource loading

Architecture & Modules

Page 8: Spring framework part 2

Architecture & Modules

Object/XMLmappingimplementationslike JAXB orXStream

JDBC – providesan abstraction layer

Programmatic ordeclarativetransactionmanagement.

ORM – providesintegration layersfor popular ORMAPIs like JPA,Hibernate oriBatis. Support ofdeclarativetransactionmanagement.

Page 9: Spring framework part 2

Instead of objects invoking other objects, the dependant objects are added through an external entity/container.

Dependencies are “injected” by container during runtime.

Beans define their dependencies through constructor arguments or properties

Dependency Injection & Inversion of Control

Page 10: Spring framework part 2

Dependency Injection & Inversion of Control

Implementation of the Inversion of Control pattern

BeanFactory responsible for instantiating all components based on a configuration

Page 11: Spring framework part 2

Spring configuration

Page 12: Spring framework part 2

Spring managed beans configuration

<?xml version="1.0" encoding="UTF-8"?><beans >

<bean id=“BookDemoService” class=“BookDemoServiceImpl”>

<property name=“dao" ref=“bookDAO”/></bean><bean id=" bookDAO " class="BookDemoDao" >

</bean>

Page 13: Spring framework part 2

Example(Dependency Injection)

public class BookDemoServiceImpl implements BookDemoService {

private BookDemoDao dao;

public void addPublisherToBook(Book book) {

String isbn = book.getIsbn(); if (book.getPublisher() == null && isbn != null) { Publisher publisher = dao.findPublisherByIsbn(isbn); book.setPublisher(publisher); }} public void setBookDemoDao(BookDemoDao dao) { this.dao = dao; } }

Page 14: Spring framework part 2

14

Lesson Summary

We have so far seen:◦ Spring Architecture and Core Module◦ IOC & Dependency Injection◦ Spring configuration’s and Examples of

Dependency Injection in Spring

Page 15: Spring framework part 2

Spring-JDBC

Page 16: Spring framework part 2

Learning Objectives

◦ Learn core functionality of Spring’s JDBC framework

◦ Understand templates and callback mechanism

◦ Understand How Spring provides a way to actually model database operations as objects

Spring-JDBC

Page 17: Spring framework part 2

Action Spring You

Define connection parameters.

X

Open the connection. X  

Specify the SQL statement.   X

Declare parameters and provide parameter values

  X

Prepare and execute the statement.

X  

Set up the loop to iterate through the results (if any).

X  

Do the work for each iteration.

  X

Process any exception. X  

Handle transactions. X  

Close the connection, statement and resultset.

X  

Spring-JDBC

Spring JDBC - who does what?

Page 18: Spring framework part 2

Problem with JDBC codepublic void GettingRows() {Connection conn=null;Statement stmt=null;Resultset rset=null;try{ conn = dataSource.getConnection(); stmt = conn.createStatement (); rset = stmt.executeQuery ("select empno, ename,job from emp");

while (rset.next()) { System.out.print (rset.getString (1));}

} catch (SQLException e) {LOGGER.error(e); throw e;

}finally{ //code to clean up resources

Declare connection parameters

Open connection

Create statement

Execute statement

Iterate over resultset

Handle exceptions

clean up resources

Page 19: Spring framework part 2

19

Using JDBC with Spring

Spring separates the fixed and variant parts of the data access process into two distinct classes: ◦ Templates: manage the fixed part of the process

like controlling transactions, managing resources,

handling exceptions etc

◦ Callbacks: define implementation details,

specific to application ie. Creating statements,

binding parameters etc

Page 20: Spring framework part 2

20

Choosing a style

There are a number of options for selecting an approach to form the basis for your JDBC database access◦ JdbcTemplate◦ NamedParameterJdbcTemplate◦ SimpleJdbcTemplate◦ SimpleJdbcInsert and SimpleJdbcCall◦ RDBMS Objects including MappingSqlQuery,

SqlUpdate and StoredProcedure

Page 21: Spring framework part 2

21

The JdbcTemplate class

Central class in JDBC framework Manages all database communication and

exception handling Based on template style of programming;

some calls are handled entirely by JdbcTemplate while others require the calling class to provide callback methods that contain implementation for parts of the JDBC workflow

Page 22: Spring framework part 2

22

The DataSource

To work with data from a database, we need to obtain a

connection to the database - through a DataSource

Many implementations of DataSource exist. Eg:

◦ BasicDataSource

◦ PoolingDataSource

◦ SingleConnectionDataSource

◦ DriverManagerDataSource The datasource can be programmatically configured. Eg

DriverManagerDataSource ds = new DriverManagerDataSource();

ds.setDriverClassName(driver); ds.setUrl(url);

ds.setUsername(username); ds.setPassword(password);

Page 23: Spring framework part 2

Configuring data sources declaratively : Eg<bean id="dataSource" class= “org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url“ value="jdbc:oracle:thin:@oraserver:1521:oradb"/> <property name="username" value="scott"/> <property name="password" value="tiger"/></bean><bean id="dataSource" class=“org.springframework.jndi.JndiObjectFactoryBean"> <property name=“jndiName" value=“/jdbc/TrgDatasource"/> <property name=“resourceRef “ value=“true"/></bean>

Page 24: Spring framework part 2

Wiring beans in the Spring context file <bean id=”jdbcTemplate”

class=”org.springframework.jdbc.core.JdbcTemplate”> <property name=”dataSource”><ref local=”

myDataSource” /> </property> </bean> <bean id=“myDataSource " <!– the datasource configuration comes here

</bean> <bean id=“jdbcTemplateDemo”

class=“JdbcTemplateDemo”> <property name= “jdbcTemplate” ref= “jdbcTemplate”

/> <bean>class JdbcTemplateDemo{public void setJdbcTemplate(JdbcTemplate jdbcTemplate){ this. jdbcTemplate= jdbcTemplate; }

Page 25: Spring framework part 2

25

JdbcTemplate : Query methods

int count = jt.queryForInt(“select count(*) from emp”);

String name = (String) jt.queryForObject("select name from

mytable where empno=1022", String.class);

List rows = jt.queryForList("select * from mytable");

Object params[] = new Object[]{new Double(1000.0)};

List rows1 = jt.queryForList(“Select * from emp where sal

> ?”,params);

JdbcTemplate jt = new JdbcTemplate(dataSource);Some examples:

Page 26: Spring framework part 2

JdbcTemplate : execute methods

public class ExecuteAStatement {

private JdbcTemplate jt, DataSource dataSource;

public void doExecute() {

jt = new JdbcTemplate(dataSource);

jt.execute("create table mytable (id integer, name

varchar(100))");

}

public void setDataSource(DataSource dataSource) {

this.dataSource = dataSource;

}

}

Page 27: Spring framework part 2

27

JdbcTemplate : update methods

int x=jt.update(“insert into Book(id,name) values(1,’Core

Java’)”);

int x=jt.update(“Update Book set name=‘Advanced Java’

where id=?”, new Object[]{new Integer(3)});

int x=jt.update(“Delete from Book where id=2”);

String sql = “insert into person(id,fname,lname) values (?,?,?)”;

Object[] params = new Object[]{ p.getId(), p.getFname(), p.getLname()};int[] types = new Int[]{Types.INTEGER, Types.VARCHAR, Types.VARCHAR};int count = jdbcTemplate.update(sql,params,types);

Some examples:

Page 28: Spring framework part 2

28

JdbcTemplate Row-handling callback interfaces

JdbcTemplate class supports the callback methods concept for performing different SQL operations.

Callback methods allow the developer to manage database operations using a higher level of abstraction.

Interfaces that can be implemented to handle the returned rows are :◦ ResultSetExtractor◦ RowCallbackHandler◦ RowMapper

Page 29: Spring framework part 2

The NamedParameterJdbcTemplate class add supports for programming JDBC statements using named parameters, as opposed to programming JDBC statements using only classic placeholder ('?') arguments.

The NamedParameterJdbcTemplate class wraps a JdbcTemplate, and delegates to the wrappedJdbcTemplate to do much of its work.

 NamedParameterJdbcTemplate

Page 30: Spring framework part 2

NamedParameterJdbcTemplate: example

// some JDBC-backed DAO class...

private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public void setDataSource(DataSource dataSource) {

this.namedParameterJdbcTemplate = new

NamedParameterJdbcTemplate(dataSource);

}

public int countOfActorsByFirstName(String firstName) {

String sql = "select count(*) from T_ACTOR where first_name = :first_name";

Map namedParameters = Collections.singletonMap("first_name", firstName);

return this.namedParameterJdbcTemplate.queryForInt(sql,

namedParameters);

}

Page 31: Spring framework part 2

31

Lesson Summary

We have so far seen:◦ How Spring’s JDBC framework offers an

excellent way to implement very low-level data access code without having to spend too much time writing tedious JDBC code.

◦ Convenience methods of the JdbcTemplate class

◦ Flexible NameParameterJdbcTemplate

style of programming using parameters ◦ Examples of JdbcTemplate and

NameParameterJdbcTemplate

Page 32: Spring framework part 2

Spring-ORM

Page 33: Spring framework part 2

The Spring Framework supports integration with Hibernate, Java Persistence API (JPA), Java Data Objects (JDO) and iBATIS SQL Maps for resource management, data access object (DAO) implementations, and transaction strategies. 

Benefits of using the Spring Framework to create your ORM DAOs

◦ Easier testing.

◦ Common data access exceptions. 

◦ General resource management.

◦ Integrated transaction management. 

 Introduction to ORM with Spring

Page 34: Spring framework part 2

In the beginning – Hibernate 2.x

Session s = HibernateUtil.getSessionFactory().getCurrentSession();

Transaction tx;try {

tx = sess.beginTransaction();//do some worktx.commit();

}catch (Exception e) {

if (tx!=null) tx.rollback();throw e;

}finally {

sess.close();}

Hibernate Integration

Page 35: Spring framework part 2

Spring came with a really nice class

Session sess = SessionFactoryUtils.getSession

(getSessionFactory(), false);

sess.save(item);

Hibernate Integration (cont.)

Page 36: Spring framework part 2

Now Hibernate 3 and Spring 3

Session s = getSessionFactory().getCurrentSession();s.save(item);

Hibernate Integration (cont.)

Page 37: Spring framework part 2

Concrete DAO class extend HibernateDaoSupport

Directly injecting a HibernateTemplate into your DAO class

Directly injecting the Hibernate SessionFactory into your DAO class◦ Possible because of Hibernate 3

3 ways to Integrate Hibernate with Spring

Page 38: Spring framework part 2

SessionFactory instead of DataSource SessionFactory setup in a Spring

container

Hibernate 3

<beans> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:hsql://localhost:9001"/> <property name="username" value="sa"/> <property name="password" value=""/> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="mappingResources"> <list> <value>product.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> </property> </bean> </beans>

Page 39: Spring framework part 2

Annotation Session Factory

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

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

<property name="hibernateProperties">

<ref bean="hibernateProjectProperties" />

</property>

<property name="annotatedClasses" ref="secFileList"/>

</bean>

Page 40: Spring framework part 2

Transaction Manager for Hibernate

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean>

Page 41: Spring framework part 2

IBatis ◦ org.springframework.orm.ibatis.SqlMapClientFacto

ryBean JPA

◦ "org.springframework.orm.jpa.LocalEntityManagerFactoryBean

JDO◦ org.springframework.orm.jdo.LocalPersistenceMan

agerFactoryBean

Other ORM Support

Page 42: Spring framework part 2

42

Lesson Summary

We have so far seen:◦ How Spring’s JDBC framework offers an

excellent way to integrate ORM Libraries

◦ How Spring Supports Transaction’s for ORM Tool

◦ Hibernate Configuration’s and annotation support and integration with Spring

◦ Examples of Hibernate Integration with Spring

Page 43: Spring framework part 2

Spring’s Transaction

Page 44: Spring framework part 2

Spring’s Transaction Why Spring Transaction Transaction Manager Programmatic Transaction Handling Declarative Transaction

◦ XML◦ @Transactional

Page 45: Spring framework part 2

Why Spring Transactions?

Page 46: Spring framework part 2

Why Spring Transaction? Uniform API On and off server Programmatic Transaction Declarative Transaction Propagation Behaviors

Page 47: Spring framework part 2

Uniform API

JDBC

Spring Transaction

ORM JCA

Application

JTA

Page 48: Spring framework part 2

On and Off Server

Spring

Java

J(2)EEContainer

ServletContainer

Spring Spring

Page 49: Spring framework part 2

Transaction Manager

Page 50: Spring framework part 2

Transaction ManagerTransactional

Resource

Transaction Manager

Page 51: Spring framework part 2

Transaction Managers Native transaction managers

◦ JDBC: DataSourceTransactionManager◦ Hibernate: HibernateTransactionManager◦ TopLink: TopLinkTransactionManager◦ JDO: JdoTransactionManager◦ etc

Native strategies work in any environment◦ but only against a single database!

no distributed transaction coordination◦ leverage full power of underlying resource

isolation levels, savepoints, etc

Page 52: Spring framework part 2

Using the TransactionTemplate. Using

PlatformTransactionManager implementation directly.

Programmatic transaction

public Object someServiceMethod() { return transactionTemplate.execute(new TransactionCallback() { // the code in this method executes in a transactional context public Object doInTransaction(TransactionStatus status) { updateOperation1(); return resultOfUpdateOperation2(); } }); }

public Object someServiceMethod() { return transactionTemplate.execute(new TransactionCallback() { // the code in this method executes in a transactional context public Object doInTransaction(TransactionStatus status) { updateOperation1(); return resultOfUpdateOperation2(); } }); }

Page 53: Spring framework part 2

Using PlatformTransactionManager

DefaultTransactionDefinition def = newDefaultTransactionDefinition(); // explicitly setting the transaction name is something that can only be done programmatically def.setName("SomeTxName"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txManager.getTransaction(def); try { // execute your business logic here } catch (MyException ex) { txManager.rollback(status); throw ex; } txManager.commit(status);

Page 54: Spring framework part 2

Adding -MyCheckedException here specifies that if the method throws MyCheckedException or any subclasses, the transaction will automatically be rolled back. Multiple rollback rules can be specified here, comma-separated. A - prefix forces rollback; a + prefix specifies commit.

Declarative Transaction<bean id="petStoreTarget"> ... </bean>

<bean id="petStore" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager" ref="txManager"/> <property name="target" ref="petStoreTarget"/> <property name="transactionAttributes"> <props> <prop key="insert*">PROPAGATION_REQUIRED,- MyCheckedException</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean>

Page 55: Spring framework part 2

Declarative Transaction with AOP

<bean id="txManager”class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>

<tx:advice id="txAdvice" transaction-manager="txManager"> <!-- the transactional semantics... --> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> <!-- >tx:method name="get" propagation="REQUIRED"/--> </tx:attributes> </tx:advice>

<aop:config proxy-target-class="true"> <aop:pointcut id="serviceOperation" expression="execution(* com.demo.springdemo.*Service.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/>

</aop:config>

Page 56: Spring framework part 2

Declarative Transaction Annotation

Page 57: Spring framework part 2

Propagation behaviors◦ MANDATORY 

          Support a current transaction, throw an exception if none exists.

◦ NESTED           Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.

◦ NEVER           Execute non-transactionally, throw an exception if a transaction exists.

◦ NOT_SUPPORTED           Execute non-transactionally, suspend the current transaction if one exists.

◦ REQUIRED           Support a current transaction, create a new one if none exists.

◦ REQUIRES_NEW           Create a new transaction, suspend the current transaction if one exists.

◦ SUPPORTS           Support a current transaction, execute non-transactionally if none exists.

Page 58: Spring framework part 2

58

Lesson Summary

We have so far seen:◦ Spring’s Transactions Benefits◦ Spring Programmatic Transactions◦ Spring Declaratives Transactions◦ Spring Declaratives Transactions with AOP◦ Spring Annotations for Transactions ◦ Spring Transactions Propagations Behavior

Page 59: Spring framework part 2

What Next!

Spring Web