SlideShare une entreprise Scribd logo
1  sur  59
By Haroon Idrees
 Recap 
 Spring-JDBC 
 Spring-ORM 
 Spring-Transactions
 Architecture & Modules 
 Dependency Injection & IOC 
 Spring configuration 
 Example
IoC and DI features based on 
the BeanFactory container 
concept 
Powerful 
language 
for querying 
and 
manipulating 
an 
object graph 
at 
runtime 
Build on the base of Beans and 
Core. Provide way to access 
objects, support for i18n, resource 
loading
JDBC – 
provides 
an abstraction 
layer 
Object/XML 
mapping 
implementations 
like JAXB or 
XStream 
Programmatic or 
declarative 
transaction 
management. 
ORM – 
provides 
integration 
layers 
for popular 
ORM 
APIs like JPA, 
Hibernate or 
iBatis. Support 
of 
declarative 
transaction 
management.
 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
 Implementation of the Inversion of Control 
pattern 
 BeanFactory responsible for instantiating all 
components based on a 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>
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; 
} 
}
14 
 We have so far seen: 
◦ Spring Architecture and Core Module 
◦ IOC & Dependency Injection 
◦ Spring configuration’s and Examples of 
Dependency Injection in Spring
 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
Action Spring You 
Define connection 
parameters. 
X 
Open the connection. X 
Specify the SQL statement. X 
Declare parameters and 
X 
provide parameter values 
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, 
X 
statement and resultset.
public void GettingRows() { 
Connection conn=null; 
Statement stmt=null; 
Resultset rset=null; 
try{ 
Declare connection parameters 
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 
Open connection 
Create statement 
Execute statement 
Iterate over resultset 
Handle exceptions 
clean up resources
 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 
19
 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, 
20 
SqlUpdate and StoredProcedure
21 
 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
 To work with data from a database, we need to obtain a 
connection to the database - through a DataSource 
22 
 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);
<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>
 <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; 
}
JdbcTemplate jt = new JdbcTemplate(dataSource); 
Some examples: 
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); 
25
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; 
} 
}
Some examples: 
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(), 
27 
p.getLname()}; 
int[] types = new Int[]{Types.INTEGER, Types.VARCHAR, 
Types.VARCHAR}; 
int count = jdbcTemplate.update(sql,params,types);
 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 
28
 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.
// 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); 
}
31 
 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
 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.
 In the beginning – Hibernate 2.x 
Session s = 
HibernateUtil.getSessionFactory().getCurrentSession(); 
Transaction tx; 
try { 
tx = sess.beginTransaction(); 
//do some work 
tx.commit(); 
} 
catch (Exception e) { 
if (tx!=null) tx.rollback(); 
throw e; 
} 
finally { 
sess.close(); 
}
 Spring came with a really nice class 
Session sess = SessionFactoryUtils.getSession 
(getSessionFactory(), false); 
sess.save(item);
 Now Hibernate 3 and Spring 3 
Session s = 
getSessionFactory().getCurrentSession(); 
s.save(item);
 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
 SessionFactory instead of DataSource 
 SessionFactory setup in a Spring container 
<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>
<bean id="sessionFactory" 
class="org.springframework.orm.hibernate3.annotation.Annotation 
SessionFactoryBean"> 
<property name="dataSource" ref="dataSource"/> 
<property name="hibernateProperties"> 
<ref bean="hibernateProjectProperties" /> 
</property> 
<property name="annotatedClasses" ref="secFileList"/> 
</bean>
<bean id="transactionManager" 
class="org.springframework.orm.hibernate3.HibernateTransaction 
Manager"> 
<property name="sessionFactory" ref="sessionFactory"/> 
</bean>
 IBatis 
◦ org.springframework.orm.ibatis.SqlMapClientFactor 
yBean 
 JPA 
◦ "org.springframework.orm.jpa.LocalEntityManagerF 
actoryBean 
 JDO 
◦ org.springframework.orm.jdo.LocalPersistenceMana 
gerFactoryBean
42 
 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
 Why Spring Transaction 
 Transaction Manager 
 Programmatic Transaction Handling 
 Declarative Transaction 
◦ XML 
◦ @Transactional
 Uniform API 
 On and off server 
 Programmatic Transaction 
 Declarative Transaction 
 Propagation Behaviors
JDBC 
Application 
Spring Transaction 
ORM JCA 
JTA
Spring 
Spring Spring 
Java 
J(2)EE 
Container 
Servlet 
Container
Transactional 
Resource 
Transaction 
Manager
 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
public Object someServiceMethod() { return transactionTemplate.execute(new TransactionCallback() { // the code in this method executes in a transactional context 
 Using the TransactionTemplate. 
 Using 
PlatformTransactionManager implementation 
directly. 
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(); 
} 
}); 
}
DefaultTransactionDefinition def = newDefaultTransactionDefinition(); 
// explicitly setting the transaction name is something that can only be 
done programmatically 
def.setName("SomeTxName"); 
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRE 
D); 
TransactionStatus status = txManager.getTransaction(def); 
try { 
// execute your business logic here 
} 
catch (MyException ex) { 
txManager.rollback(status); throw ex; 
} 
txManager.commit(status);
<bean id="petStoreTarget"> ... </bean> 
<bean id="petStore" 
class="org.springframework.transaction.interceptor.TransactionProxy 
FactoryBean"> 
<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> 
 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.
<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>
◦ 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.
58 
 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
Spring Web

Contenu connexe

Tendances

An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate TutorialRam132
 
Wed 1630 greene_robert_color
Wed 1630 greene_robert_colorWed 1630 greene_robert_color
Wed 1630 greene_robert_colorDATAVERSITY
 
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...Cloudera, Inc.
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsosa_ora
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceNiraj Bharambe
 
Apache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei BatisApache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei Batisday
 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationKhoa Nguyen
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)ejlp12
 
2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the ContextRussell Castagnaro
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentationJohn Slick
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracleyazidds2
 
Entity Persistence with JPA
Entity Persistence with JPAEntity Persistence with JPA
Entity Persistence with JPASubin Sugunan
 

Tendances (20)

An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Wed 1630 greene_robert_color
Wed 1630 greene_robert_colorWed 1630 greene_robert_color
Wed 1630 greene_robert_color
 
Hibernate
HibernateHibernate
Hibernate
 
Spring Data in 10 minutes
Spring Data in 10 minutesSpring Data in 10 minutes
Spring Data in 10 minutes
 
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tips
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
 
Jpa 2.1 Application Development
Jpa 2.1 Application DevelopmentJpa 2.1 Application Development
Jpa 2.1 Application Development
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
 
Apache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei BatisApache Con Us2007 Apachei Batis
Apache Con Us2007 Apachei Batis
 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - Presentation
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)
 
2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the Context
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
Ajax
AjaxAjax
Ajax
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Entity Persistence with JPA
Entity Persistence with JPAEntity Persistence with JPA
Entity Persistence with JPA
 

Similaire à Spring framework part 2

jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.pptDrMeenakshiS
 
Spring db-access mod03
Spring db-access mod03Spring db-access mod03
Spring db-access mod03Guo Albert
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3IMC Institute
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedIMC Institute
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programmingchhaichivon
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsFulvio Corno
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Zianed Hou
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5Smita B Kumar
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
 

Similaire à Spring framework part 2 (20)

Jdbc
JdbcJdbc
Jdbc
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
JDBC
JDBCJDBC
JDBC
 
Spring db-access mod03
Spring db-access mod03Spring db-access mod03
Spring db-access mod03
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
JDBC in Servlets
JDBC in ServletsJDBC in Servlets
JDBC in Servlets
 
Java beans
Java beansJava beans
Java beans
 
Data access
Data accessData access
Data access
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 

Dernier

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 

Dernier (20)

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 

Spring framework part 2

  • 2.  Recap  Spring-JDBC  Spring-ORM  Spring-Transactions
  • 3.
  • 4.  Architecture & Modules  Dependency Injection & IOC  Spring configuration  Example
  • 5.
  • 6.
  • 7. IoC and DI features based on the BeanFactory container concept Powerful language for querying and manipulating an object graph at runtime Build on the base of Beans and Core. Provide way to access objects, support for i18n, resource loading
  • 8. JDBC – provides an abstraction layer Object/XML mapping implementations like JAXB or XStream Programmatic or declarative transaction management. ORM – provides integration layers for popular ORM APIs like JPA, Hibernate or iBatis. Support of declarative transaction management.
  • 9.  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
  • 10.  Implementation of the Inversion of Control pattern  BeanFactory responsible for instantiating all components based on a configuration
  • 11.
  • 12. <?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>
  • 13. 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; } }
  • 14. 14  We have so far seen: ◦ Spring Architecture and Core Module ◦ IOC & Dependency Injection ◦ Spring configuration’s and Examples of Dependency Injection in Spring
  • 15.
  • 16.  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
  • 17. Action Spring You Define connection parameters. X Open the connection. X Specify the SQL statement. X Declare parameters and X provide parameter values 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, X statement and resultset.
  • 18. public void GettingRows() { Connection conn=null; Statement stmt=null; Resultset rset=null; try{ Declare connection parameters 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 Open connection Create statement Execute statement Iterate over resultset Handle exceptions clean up resources
  • 19.  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 19
  • 20.  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, 20 SqlUpdate and StoredProcedure
  • 21. 21  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
  • 22.  To work with data from a database, we need to obtain a connection to the database - through a DataSource 22  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);
  • 23. <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>
  • 24.  <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; }
  • 25. JdbcTemplate jt = new JdbcTemplate(dataSource); Some examples: 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); 25
  • 26. 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; } }
  • 27. Some examples: 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(), 27 p.getLname()}; int[] types = new Int[]{Types.INTEGER, Types.VARCHAR, Types.VARCHAR}; int count = jdbcTemplate.update(sql,params,types);
  • 28.  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 28
  • 29.  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.
  • 30. // 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); }
  • 31. 31  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
  • 32.
  • 33.  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.
  • 34.  In the beginning – Hibernate 2.x Session s = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx; try { tx = sess.beginTransaction(); //do some work tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); throw e; } finally { sess.close(); }
  • 35.  Spring came with a really nice class Session sess = SessionFactoryUtils.getSession (getSessionFactory(), false); sess.save(item);
  • 36.  Now Hibernate 3 and Spring 3 Session s = getSessionFactory().getCurrentSession(); s.save(item);
  • 37.  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
  • 38.  SessionFactory instead of DataSource  SessionFactory setup in a Spring container <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>
  • 39. <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.Annotation SessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <ref bean="hibernateProjectProperties" /> </property> <property name="annotatedClasses" ref="secFileList"/> </bean>
  • 40. <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransaction Manager"> <property name="sessionFactory" ref="sessionFactory"/> </bean>
  • 41.  IBatis ◦ org.springframework.orm.ibatis.SqlMapClientFactor yBean  JPA ◦ "org.springframework.orm.jpa.LocalEntityManagerF actoryBean  JDO ◦ org.springframework.orm.jdo.LocalPersistenceMana gerFactoryBean
  • 42. 42  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
  • 43.
  • 44.  Why Spring Transaction  Transaction Manager  Programmatic Transaction Handling  Declarative Transaction ◦ XML ◦ @Transactional
  • 45.
  • 46.  Uniform API  On and off server  Programmatic Transaction  Declarative Transaction  Propagation Behaviors
  • 47. JDBC Application Spring Transaction ORM JCA JTA
  • 48. Spring Spring Spring Java J(2)EE Container Servlet Container
  • 49.
  • 51.  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
  • 52. public Object someServiceMethod() { return transactionTemplate.execute(new TransactionCallback() { // the code in this method executes in a transactional context  Using the TransactionTemplate.  Using PlatformTransactionManager implementation directly. 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(); } }); }
  • 53. DefaultTransactionDefinition def = newDefaultTransactionDefinition(); // explicitly setting the transaction name is something that can only be done programmatically def.setName("SomeTxName"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRE D); TransactionStatus status = txManager.getTransaction(def); try { // execute your business logic here } catch (MyException ex) { txManager.rollback(status); throw ex; } txManager.commit(status);
  • 54. <bean id="petStoreTarget"> ... </bean> <bean id="petStore" class="org.springframework.transaction.interceptor.TransactionProxy FactoryBean"> <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>  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.
  • 55. <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>
  • 56.
  • 57. ◦ 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.
  • 58. 58  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