1 (Template Class) | 2 (Dao Support Class)
Spring provides two ways in which we can integrate Spring with the JDBC.
1) Template Classes
2) DaoSupport Class
Consider this plain JDBC example which performs CRUD operations.
In the above example you will note that:
1) There is lot of code repeated many times such as obtaining connections, closing the resources, exception handling.
2) Here it is your responsibility to catch SQLExceptions. (Note that SQLException is a checked exception. It is necessary to catch it).
3) Here you are managing the resources (i.e opening & closing of connections, statements etc. )
All this is known as boilerplate code. Though Boilerplate code takes up lot of space and developers attention, but still it is necessary and important.While integrating with any database technology, Spring framework relieves the developer from handling bolierplate code and let him focus on the main business logic.
Lets see how Template classes and DaoSupport Class can be used.
1. Template Class
Template class takes the responsibilty of
a) Handling of resources (opening / closing of connections etc.).
b) Converting SQLExceptions to Spring data access exceptions. Since Spring exceptions are runtime unchecked exceptions, developer do not need to catch them.
Developer only calls methods on template object to do database operations.
Spring comes with three types of template classes
1) JdbcTemplate
2) NamedParameterJdbcTemplate
3) SimpleJdbcTemplate
Here I am using the first one - JdbcTemplate.
The basic structure of dependencies is:
Step1: Register the Datasource in ApplicationContext.xml
For using the templates first you have to register a datasource.
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/examples" />
<property name="username" value="root" />
<!-- change 'root' with your password -->
<property name="password" value="root" />
</bean>
In this example I am using mysql database -examples whose structure is given here at complete example.
Step2: Register the Template class
Now register Template class and inject datasource into it. Here we have used JdbcTemplate class.
<bean id="myJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="myDataSource" />
</bean>
Step3: Regsister the Dao
Now inject the template into your dao class.
<bean id="myIssueDao" class="examples.springjdbc.dao.IssuesDaoImpl">
<property name="jdbcTemplate" ref="myJdbcTemplate"/>
</bean>
The code snippet of Dao class is:
public class IssuesDaoImpl implements IssuesDao{
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
...
}
Here we are using setter method for injecting the template into the dao.
Step 4: Use the Template in your dao
public class IssuesDaoImpl implements IssuesDao{
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
public void addIssue(Issue issue){
String sql = "insert into issue(assigned_to,assigned_by,status) values (?,?,?)";
jdbcTemplate.update(sql,issue.getAssigned_to(),issue.getAssigned_by (),issue.getStatus());
}
...
}
Note that in the dao there is no resource management code like opening and closing of connections. All that is handled by JdbcTemplate. We only called update() method on JdbcTemplate to update the record.
Complete example is given here along with explanation.
1 (Template Class) | 2 (Dao Support Class)
Spring provides two ways in which we can integrate Spring with the JDBC.
1) Template Classes
2) DaoSupport Class
Consider this plain JDBC example which performs CRUD operations.
public class IssueDao {
String url="jdbc:mysql://localhost:3306/examples";
String user="root";
String password="root";
PreparedStatement pstmt=null;
Statement stmt=null;
Connection con=null;
ResultSet rs= null;
public IssueDao(){
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
System.out.println(e);
}
}
/*Create*/
public void insertIssue(){
String sql="insert into issue values(?,?,?,?)";
try{
con= DriverManager.getConnection(url,user,password);
pstmt= con.prepareStatement(sql);
pstmt.setInt(1,1);
pstmt.setString(2,"Mr.Z");
pstmt.setString(3,"Mr.T");
pstmt.setString(4,"Open");
pstmt.executeUpdate();
}catch(SQLException e){
System.out.println(e);
}
finally{
try{
if(pstmt!=null){
pstmt.close();
}
if(con!=null){
con.close();
}
}catch(SQLException e){
System.out.println(e);
}
}
}
/*Retrieve*/
public void getIssues(){
String sql="Select * from issue";
try{
con= DriverManager.getConnection(url,user,password);
stmt= con.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.print("ID:="+rs.getInt("tid"));
System.out.print(" Assigned To:="+rs.getString("assigned_to"));
System.out.print(" Assigned By:="+rs.getString("assigned_by"));
System.out.println(" Status:="+rs.getString("status"));
}
}catch(SQLException e){
System.out.println(e);
}
finally{
try{
if(stmt!=null){
stmt.close();
}
if(con!=null){
con.close();
}
}catch(SQLException e){
System.out.println(e);
}
}
}
/*Update*/
public void updateIssue(){
String sql="update issue set status=? where tid=?";
try{
con= DriverManager.getConnection(url,user,password);
pstmt= con.prepareStatement(sql);
pstmt.setString(1,"Closed");
pstmt.setInt(2,1);
pstmt.executeUpdate();
}catch(SQLException e){
System.out.println(e);
}
finally{
try{
if(pstmt!=null){
pstmt.close();
}
if(con!=null){
con.close();
}
}catch(SQLException e){
System.out.println(e);
}
}
}
/*Delete*/
public void deleteIssue(){
String sql="delete from issue where tid=?";
try{
con= DriverManager.getConnection(url,user,password);
pstmt= con.prepareStatement(sql);
pstmt.setInt(1,1);
pstmt.executeUpdate();
}catch(SQLException e){
System.out.println(e);
}
finally{
try{
if(pstmt!=null){
pstmt.close();
}
if(con!=null){
con.close();
}
}catch(SQLException e){
System.out.println(e);
}
}
}
}
String url="jdbc:mysql://localhost:3306/examples";
String user="root";
String password="root";
PreparedStatement pstmt=null;
Statement stmt=null;
Connection con=null;
ResultSet rs= null;
public IssueDao(){
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
System.out.println(e);
}
}
/*Create*/
public void insertIssue(){
String sql="insert into issue values(?,?,?,?)";
try{
con= DriverManager.getConnection(url,user,password);
pstmt= con.prepareStatement(sql);
pstmt.setInt(1,1);
pstmt.setString(2,"Mr.Z");
pstmt.setString(3,"Mr.T");
pstmt.setString(4,"Open");
pstmt.executeUpdate();
}catch(SQLException e){
System.out.println(e);
}
finally{
try{
if(pstmt!=null){
pstmt.close();
}
if(con!=null){
con.close();
}
}catch(SQLException e){
System.out.println(e);
}
}
}
/*Retrieve*/
public void getIssues(){
String sql="Select * from issue";
try{
con= DriverManager.getConnection(url,user,password);
stmt= con.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.print("ID:="+rs.getInt("tid"));
System.out.print(" Assigned To:="+rs.getString("assigned_to"));
System.out.print(" Assigned By:="+rs.getString("assigned_by"));
System.out.println(" Status:="+rs.getString("status"));
}
}catch(SQLException e){
System.out.println(e);
}
finally{
try{
if(stmt!=null){
stmt.close();
}
if(con!=null){
con.close();
}
}catch(SQLException e){
System.out.println(e);
}
}
}
/*Update*/
public void updateIssue(){
String sql="update issue set status=? where tid=?";
try{
con= DriverManager.getConnection(url,user,password);
pstmt= con.prepareStatement(sql);
pstmt.setString(1,"Closed");
pstmt.setInt(2,1);
pstmt.executeUpdate();
}catch(SQLException e){
System.out.println(e);
}
finally{
try{
if(pstmt!=null){
pstmt.close();
}
if(con!=null){
con.close();
}
}catch(SQLException e){
System.out.println(e);
}
}
}
/*Delete*/
public void deleteIssue(){
String sql="delete from issue where tid=?";
try{
con= DriverManager.getConnection(url,user,password);
pstmt= con.prepareStatement(sql);
pstmt.setInt(1,1);
pstmt.executeUpdate();
}catch(SQLException e){
System.out.println(e);
}
finally{
try{
if(pstmt!=null){
pstmt.close();
}
if(con!=null){
con.close();
}
}catch(SQLException e){
System.out.println(e);
}
}
}
}
In the above example you will note that:
1) There is lot of code repeated many times such as obtaining connections, closing the resources, exception handling.
2) Here it is your responsibility to catch SQLExceptions. (Note that SQLException is a checked exception. It is necessary to catch it).
3) Here you are managing the resources (i.e opening & closing of connections, statements etc. )
All this is known as boilerplate code. Though Boilerplate code takes up lot of space and developers attention, but still it is necessary and important.While integrating with any database technology, Spring framework relieves the developer from handling bolierplate code and let him focus on the main business logic.
Lets see how Template classes and DaoSupport Class can be used.
1. Template Class
Template class takes the responsibilty of
a) Handling of resources (opening / closing of connections etc.).
b) Converting SQLExceptions to Spring data access exceptions. Since Spring exceptions are runtime unchecked exceptions, developer do not need to catch them.
Developer only calls methods on template object to do database operations.
Spring comes with three types of template classes
1) JdbcTemplate
2) NamedParameterJdbcTemplate
3) SimpleJdbcTemplate
Here I am using the first one - JdbcTemplate.
The basic structure of dependencies is:
Step1: Register the Datasource in ApplicationContext.xml
For using the templates first you have to register a datasource.
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/examples" />
<property name="username" value="root" />
<!-- change 'root' with your password -->
<property name="password" value="root" />
</bean>
In this example I am using mysql database -examples whose structure is given here at complete example.
Step2: Register the Template class
Now register Template class and inject datasource into it. Here we have used JdbcTemplate class.
<bean id="myJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="myDataSource" />
</bean>
Step3: Regsister the Dao
Now inject the template into your dao class.
<bean id="myIssueDao" class="examples.springjdbc.dao.IssuesDaoImpl">
<property name="jdbcTemplate" ref="myJdbcTemplate"/>
</bean>
The code snippet of Dao class is:
public class IssuesDaoImpl implements IssuesDao{
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
...
}
Here we are using setter method for injecting the template into the dao.
Step 4: Use the Template in your dao
public class IssuesDaoImpl implements IssuesDao{
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
public void addIssue(Issue issue){
String sql = "insert into issue(assigned_to,assigned_by,status) values (?,?,?)";
jdbcTemplate.update(sql,issue.getAssigned_to(),issue.getAssigned_by (),issue.getStatus());
}
...
}
Note that in the dao there is no resource management code like opening and closing of connections. All that is handled by JdbcTemplate. We only called update() method on JdbcTemplate to update the record.
Complete example is given here along with explanation.
1 (Template Class) | 2 (Dao Support Class)
I would like to know your comments and if you liked the article then please share it on social networking buttons.
No comments:
Post a Comment