Nearby lessons

14 of 35

Spring - JDBC / DAO

📌 What You Will Learn
  • Understand Spring - JDBC / DAO
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - JDBC / DAO step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Provide an implementation to DAO interface

public class StudentDAOImpl implements StudentDao{ ---implementation for all StudentDao interface methods----- ---> We can provide our methods inorder to improve code reusability along with DAO interface methods--- }

Prepare DTOs as per the requirement

public class Student{ private String sid; private String sname; private String saddr; ----- ----- setXXX() and getXXX() ----- ----- }

Creat Factory Methods/ Factory Classes to generate DAOs

public class StudentDaoFactory{ private static Student Dao dao; static{ dao = new StudentDaoImpl(); } public static StudentDao getStudentDao(){ return dao; } }

In Service layer StudentDao dao = StudentDao.getStudentDao();

5) We must not cache DAO references, because, Factory classes/ Factory methods are providing single instances of DAO to the service layer, if DAO is required in multiple modules then it is requyired to create more than one DAO reference.

6) In case of DAOs, It is suggestible to interact with Databases by using Connection Pooling mechanisms, not by using DriverManager approach. 7) DAO is not threadsafe, we must not use DAOs in multi threadded environment.

8) In DAOs we can access close() method inorder to close the resources like connections,.... , so here, before calling close() method we must ensure that whether the resources are going to be released or not with our close() method call.

9) We have make sure that all the objects which are used by DAOs are following Java bean conventions or not.

htmls

a)addform.html b)searchform.html c)deleteform.html d)existed.html e)notexisted.html f)success.html g)failure.html h)layout.html i)header.html j)menu.html k)welcome.html l)footer.html

  • jsps a)display.jsp
  • Servlets a)ControllerServlet
  • Services:

a)StudentService

  • DAOs a)StudentDao

6)DTOs a)StudentTo

7)Factories a)ConnectionFactory b)StudentServiceFactory c)StudentDaoFactory

JARS

a)ojdbc6.jar

Design Patterns — layout.html

a)DAO b)MVC c)DTO d)Factory

Example:

Example06
JCode Cell
1 
2<frameset rows="20%,65%,15%">
3 <frame src="header.html"/>
4 <frameset cols="20%,80%">
5 <frame src="menu.html"/>
6 <frame src="welcome.html" name="body"/>
7 </frameset>
8 <frame src="footer.html"/>
9 
10</frameset>
11

Design Patterns — header.html

Example07
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3"http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body bgcolor="maroon">
10<center>
11<font color="white" size="7">
12<b>
13DURGA SOFTWARE SOLUTIONS
14</b>
15</font>
16</center>
17</body>
18</html>
19

Design Patterns — footer.html

Example08
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3"http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body bgcolor="blue">
10<center>
11<font color="white" size="5">
12<b>
13

Design Patterns — menu.html

Durga Software Solutions, 202, Mitrivanam, Ameerpet, Hyd-38 </b> </font> </center> </body> </html>

Example09
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3"http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body bgcolor="lightyellow">
10<center>
11<h3>
12<br><br>
13<a href="./addform.html" target="body">Add Student</a><br><br>
14<a href="./searchform.html" target="body">Search Student</a><br><br>
15<a href="./deleteform.html" target="body">Delete Student</a>
16</h3>
17</center>
18</body>
19</html>
20

Design Patterns — welcome.html

Example10
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3"http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body bgcolor="lightblue">
10<center>
11<br><br><br>
12<font color="red" size="6">
13<b>
14<marquee>
15

Design Patterns — addform.html

Welcome To Durga Software Solutions </marquee> </b> </font> </center> </body> </html>

Example11
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3"http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body bgcolor="lightblue">
10<form method="POST" action="./controller">
11<center>
12<br><br><br>
13<table>
14<tr>
15 
16 <td>Student Id</td><td><input type="text" name="sid"/></td>
17</tr>
18<tr>
19 
20 <td>Student Name</td><td><input type="text" name="sname"/></td>
21</tr>
22<tr>
23 
24 <td>Student Address</td><td><input type="text" name="saddr"/></td>
25</tr>
26<tr>
27 
28 <td><input type="submit" value="ADD" name="button"/>
29</tr>
30</table>
31</center>
32</form>
33</body>
34</html>
35

Design Patterns — searchform.html

Example12
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3"http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body bgcolor="lightblue">
10<form method="POST" action="./controller">
11<br><br><br>
12<center>
13<table>
14<tr>
15 
16 <td>Student Id</td><td><input type="text" name="sid"/></td>
17</tr>
18<tr>
19 
20 <td><input type="submit" value="SEARCH" name="button"/></td>
21</tr>
22</table>
23</center>
24</form>
25</body>
26</html>
27

Design Patterns — deleteform.html

Example13
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3"http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body bgcolor="lightblue">
10<form method="POST" action="./controller">
11<br><br><br>
12<center>
13<table>
14<tr>
15 
16 <td>Student Id</td><td><input type="text" name="sid"/></td>
17</tr>
18<tr>
19 
20 <td><input type="submit" value="DELETE" name="button"/></td>
21</tr>
22</table>
23</center>
24</form>
25</body>
26</html>
27

Design Patterns — display.jsp

Example14
JCode Cell
1 
2<%@page import="com.durgasoft.to.StudentTo"%>
3<%!
4StudentTo sto;
5%>
6<%
7sto = (StudentTo)request.getAttribute("sto");
8%>
9<html>
10<body bgcolor="lightblue">
11<center>
12<br><br><br>
13<table border = "1" bgcolor="white">
14<tr>
15 
16 <td>Student Id</td><td><%= sto.getSid() %></td>
17</tr>
18<tr>
19 
20 <td>Student Name</td><td><%= sto.getSname() %></td>
21</tr>
22<tr>
23 
24 <td>Student Address</td><td><%= sto.getSaddr() %></td>
25</tr>
26 
27</table>
28</center>
29</body>
30</html>
31

Design Patterns — existed.html

Example15
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3"http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body bgcolor="lightblue">
10<center>
11<br><br><br>
12<font color="red" size="6">
13<b>
14Student Existed Already
15</b>
16</font>
17</center>
18</body>
19</html>
20

Design Patterns — notexisted.html

Example16
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3"http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body bgcolor="lightblue">
10<center>
11<br><br><br>
12<font color="red" size="6">
13<b>
14Student Not Existed
15</b>
16</font>
17</center>
18</body>
19</html>
20

Design Patterns — success.html

Example17
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3"http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body bgcolor="lightblue">
10<center>
11<br><br><br>
12<font color="red" size="6">
13<b>
14Success
15</b>
16</font>
17</center>
18</body>
19</html>
20

Design Patterns — failure.html

Example18
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3"http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7<title>Insert title here</title>
8</head>
9<body bgcolor="lightblue">
10<center>
11<br><br><br>
12<font color="red" size="6">
13<b>
14Failure
15</b>
16</font>
17</center>
18</body>
19</html>
20

Design Patterns — ControllerServlet.java

Example19
JCode Cell
1 
2package com.durgasoft.controller;
3import java.io.IOException;
4 
5import javax.servlet.RequestDispatcher;
6import javax.servlet.ServletException;
7import javax.servlet.http.HttpServlet;
8import javax.servlet.http.HttpServletRequest;
9import javax.servlet.http.HttpServletResponse;
10 
11import com.durgasoft.factory.StudentServiceFactory;
12import com.durgasoft.services.StudentService;
13import com.durgasoft.to.StudentTo;
14public class ControllerServlet extends HttpServlet {
15 
16 private static final long serialVersionUID = 1L;
17 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
18ServletException, IOException {
19 
20 String button_Label = request.getParameter("button");
21 String status = "";
22 RequestDispatcher rd = null;
23 if(button_Label.equals("ADD")){
24 
25 StudentService service = StudentServiceFactory.getStudentService();
26 StudentTo sto = new StudentTo();
27 sto.setSid(request.getParameter("sid"));
28 sto.setSname(request.getParameter("sname"));
29 sto.setSaddr(request.getParameter("saddr"));
30 status = service.addStudent(sto);
31 if(status.equals("success")){
32 
33 rd = request.getRequestDispatcher("./success.html");
34 rd.forward(request, response);
35 }
36 if(status.equals("failure")){
37 rd = request.getRequestDispatcher("./failure.html");
38 rd.forward(request, response);
39 }
40 if(status.equals("existed")){
41 rd = request.getRequestDispatcher("./existed.html");
42 rd.forward(request, response);
43 }
44 }
45 if(button_Label.equals("SEARCH")){
46 String sid = request.getParameter("sid");
47 StudentService service = StudentServiceFactory.getStudentService();
48 StudentTo sto = service.searchStudent(sid);
49 RequestDispatcher dispatcher = null;
50 if( sto == null) {
51 dispatcher = request.getRequestDispatcher("notexisted.html");
52 dispatcher.forward(request, response);
53 }else {
54 request.setAttribute("sto", sto);
55 dispatcher = request.getRequestDispatcher("display.jsp");
56 dispatcher.forward(request, response);
57 }
58 }
59 if(button_Label.equals("DELETE")){
60 String sid = request.getParameter("sid");
61 StudentService service = StudentServiceFactory.getStudentService();
62 status = service.deleteStudent(sid);
63 RequestDispatcher dispatcher = null;
64 if( status.equals("success")) {
65 dispatcher = request.getRequestDispatcher("success.html");
66 dispatcher.forward(request, response);
67 }
68 if( status.equals("failure")) {
69 dispatcher = request.getRequestDispatcher("failure.html");
70 dispatcher.forward(request, response);
71 }
72 if( status.equals("notexisted")) {
73 
74 dispatcher = request.getRequestDispatcher("notexisted.html");
75 dispatcher.forward(request, response);
76 }
77 }
78 }
79 
80}
81

Design Patterns — StudentService.java

Example20
JCode Cell
1 
2package com.durgasoft.services;
3 
4import com.durgasoft.to.StudentTo;
5 
6public interface StudentService {
7 public String addStudent(StudentTo sto);
8 public StudentTo searchStudent(String sid);
9 public String deleteStudent(String sid);
10 
11}
12

Design Patterns — StudentServiceImpl.java

Example21
JCode Cell
1 
2package com.durgasoft.services;
3 
4import com.durgasoft.dao.StudentDao;
5import com.durgasoft.factory.StudentDaoFactory;
6import com.durgasoft.to.StudentTo;
7 
8public class StudentServiceImpl implements StudentService {
9 String status="";
10 @Override
11 public String addStudent(StudentTo sto) {
12 StudentDao dao = StudentDaoFactory.getStudentDao();
13 status = dao.add(sto);
14 return status;
15 }
16 
17@Override
18public StudentTo searchStudent(String sid) {
19 
20 StudentTo sto = null;
21 StudentDao dao = StudentDaoFactory.getStudentDao();
22 sto = dao.search(sid);
23 return sto;
24}
25 
26@Override
27public String deleteStudent(String sid) {
28 
29 StudentDao dao = StudentDaoFactory.getStudentDao();
30 status = dao.delete(sid);
31 return status;
32}
33}
34

Design Patterns — StudentDao.java

Example22
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import com.durgasoft.to.StudentTo;
5 
6public interface StudentDao {
7 public String add(StudentTo sto);
8 public StudentTo search(String sid);
9 public String delete(String sid);
10 
11}
12

Design Patterns — StudentDaoImpl.java

Example23
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import java.sql.Connection;
5import java.sql.PreparedStatement;
6import java.sql.ResultSet;
7 
8import com.durgasoft.factory.ConnectionFactrory;
9import com.durgasoft.to.StudentTo;
10 
11public class StudentDaoImpl implements StudentDao{
12 String status = "";
13 @Override
14 public String add(StudentTo sto) {
15 try {
16 Connection con = ConnectionFactrory.getConnection();
17 PreparedStatement pst = con.prepareStatement("select * from student where
18 
19sid = ?");
20 pst.setString(1, sto.getSid());
21 ResultSet rs = pst.executeQuery();
22 boolean b = rs.next();
23 if( b == true ) {
24 status = "existed";
25 }else {
26 pst = con.prepareStatement("insert into student values(?,?,?)");
27 pst.setString(1,sto.getSid());
28 pst.setString(2, sto.getSname());
29 pst.setString(3, sto.getSaddr());
30 pst.executeUpdate();
31 status = "success";
32 }
33 } catch (Exception e) {
34 status = "failure";
35 e.printStackTrace();
36 }
37 return status;
38 }
39 @Override
40 public StudentTo search(String sid) {
41 StudentTo sto = null;
42 try {
43 Connection con = ConnectionFactrory.getConnection();
44 PreparedStatement pst = con.prepareStatement("select * from student where
45sid = ?");
46 pst.setString(1, sid);
47 ResultSet rs = pst.executeQuery();
48 boolean b = rs.next();
49 if(b == true) {
50 sto = new StudentTo();
51 sto.setSid(rs.getString("SID"));
52 sto.setSname(rs.getString("SNAME"));
53 sto.setSaddr(rs.getString("SADDR"));
54 }else {
55 sto = null;
56 }
57 } catch (Exception e) {
58 e.printStackTrace();
59 }
60 return sto;
61 }
62 @Override
63 public String delete(String sid) {
64 try {
65 Connection con = ConnectionFactrory.getConnection();
66 PreparedStatement pst = con.prepareStatement("select * from student where
67sid = ?");
68 pst.setString(1, sid);
69 ResultSet rs = pst.executeQuery();
70 boolean b = rs.next();
71 if(b == true) {
72 pst = con.prepareStatement("delete from student where sid = ?");
73 pst.setString(1, sid);
74 pst.executeUpdate();
75 status = "success";
76 }else {
77 status = "notexisted";
78 }
79 } catch (Exception e) {
80 status = "failure";
81 e.printStackTrace();
82 }
83 return status;
84 }
85}
86

Design Patterns — StudentTo.java

Example24
JCode Cell
1 
2package com.durgasoft.to;
3 
4public class StudentTo {
5 private String sid;
6 private String sname;
7 private String saddr;
8 
9 public String getSid() {
10 return sid;
11 
12 }
13 public void setSid(String sid) {
14 
15 this.sid = sid;
16 }
17 public String getSname() {
18 
19 return sname;
20 }
21 public void setSname(String sname) {
22 
23 this.sname = sname;
24 }
25 public String getSaddr() {
26 
27 return saddr;
28 }
29 public void setSaddr(String saddr) {
30 
31 this.saddr = saddr;
32 }
33 
34}
35

Design Patterns — StudentServiceFactory.java

Example25
JCode Cell
1 
2package com.durgasoft.factory;
3 
4import com.durgasoft.services.StudentService;
5import com.durgasoft.services.StudentServiceImpl;
6 
7public class StudentServiceFactory {
8 private static StudentService service;
9 static{
10 service = new StudentServiceImpl();
11 }
12 public static StudentService getStudentService(){
13 return service;
14 }
15 
16}
17

Design Patterns — StudentDaoFactory.java

Example26
JCode Cell
1 
2package com.durgasoft.factory;
3 
4import com.durgasoft.dao.StudentDao;
5import com.durgasoft.dao.StudentDaoImpl;
6 
7public class StudentDaoFactory {
8 private static StudentDao dao;
9 static {
10 dao = new StudentDaoImpl();
11 }
12 public static StudentDao getStudentDao() {
13 return dao;
14 }
15 
16}
17

Design Patterns — ConnectionFactory.java

Example27
JCode Cell
1 
2package com.durgasoft.factory;
3 
4import java.sql.Connection;
5import java.sql.DriverManager;
6 
7public class ConnectionFactrory {
8 private static Connection con;
9 static {
10 
11 try {
12 Class.forName("oracle.jdbc.OracleDriver");
13 con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
14 
15"system", "durga");
16 } catch (Exception e) {
17 e.printStackTrace();
18 }
19 
20 }
21 public static Connection getConnection() {
22 
23 return con;
24 }
25}
26

Design Patterns

To provide support for DAOs kind of implementations in Spring Applications, Spring has provided a separate module called as ―Spring DAO‖. Spring DAO modules has provided a set of predefined classes and interfaces in order to provide DAO support in the form of ―org.springframework.dao‖ package.

Spring provides a convenient translation from technology-specific exceptions like SQLException , HibernateException,…… to its own exception class hierarchy with the DataAccessException as the root exception. Spring JDBC

In Enterprise Applications, to prepare Data Access Layer or DAO layer Spring has provided Modules in the form of JDBC and ORM . IN ORM we may use no of ORM implementation tools like Hibernate, JPA, Ibatis,....

Q)In Enterprise Applications, to prepare Data Access Layer we have already Plain JDBC tech. then what is the requirement to go for Spring JDBC Module?

Ans — StudentDao.java

  • To prepare Data Access Layer in enterprise applications, if we use JDBC then we must take explicit responsibility to prepare the steps load and register the driver, Establisg Connection, creating Statement, executing SQl Queries and closing the resources like ResultSet, Statement and Connection.

If we use Spring JDBC module to prepare Data Access Layer, we must take explicit responsibility to write and execute SQL Queries only, not to take any responsibility to load and register driver, connection establishment, creating Statement and closing the resources.

  • In case of Plain JDBC, almost all the exceptions are checked exceptions, we have to handle them explicitly by providing some java code.

In case of Spring JDBC module, all the internal checked exceptions are converted into Unchecked Exceptions which are defined by Spring DAO module , it is very simple to handle these unchecked Exceptions.

  • In Plain JDBC, limited support is available for Transactions.

In Spring JDBC Module, very good support is available for transactions, we may use Transaction module also to provide transactions.

  • In Plain JDBC, to hold the results we are able to use only ResultSet object, which is not implementing java.io.Serializable interface, which is not transferable in network.

In Spring JDBC, we are able to get results of SQL Queries in our required form like in the form of RowSet, Collections, ..... which are implementing java.io.Serializable interface and which are transferable in Network.

  • In plain JDBC, we are able to get Connections either by using DriverManager or by using Datasource.

In Spring JDBC, we are able to get Connection internally by using Datasource only, that is through Connection Pooling only.

  • In plain JDBC, to map records to Bean objects in the form of Collection Object we have to write java code explicitly, no predefined support is provided by JDBC tech.

In case of Spring JDBC, to map Database records to Bean objects in the form of Collection Spring JDBC has provided predefined support in the form of "RowMapper".

  • In Plain JDBC, no callback interfaces support is available to create and execute the sql queries in PrfeparedStatement style.

In Spring JDBC, callback interfaces support is available to create and execute sql queries in PreparedStatement style.

To prepare Data Access Layer in enterprise applications, Spring JDBC module has provided the complete predefined library in the from of the following classes and interfaces in "org.springframework.jdbc" and its sub packages.

JdbcTemplate NamedParameterJdbcTemplate SimpleJdbcTemplate SimpleJdbcInsert and SimpleJdbcCall SQL Mapping through SQLUpdate and SQLInsert

In Spring Applications, if we want to JdbcTemplate[Jdbc Module] then we have to use the following steps.

1)Create DAO interface with the required methods. 2)Create DAO implementation class with implementation for DAO interface methods. 3)In Configuration File provide configuration for DataSource class , JdbcTemplate class and DAO implementation class. 4)Prepare Test Application to access Dao methods.

IN Spring configuration file we have to configure DataSource with the following properties.

driverClassName url username password In Spring applications, to configure DataSource Spring has provided a seperate a predefined Datasource class in the form of "org.springframework.jdbc.datasource.DriverManagerDataSource", it is not suggestible for production mode, it is suggestible for testing mode of our applications , In spring applications, it is always suggestible to use third party Connection Pooling mechanisms like dbcp, C3P0, Proxool,..

JdbcTemplate class is providing basic environment to interact with Database like Loading Driver class, Getting Connection between Java application and DB, Creating Statement , PreparedStatement and CallableStatement and closing the connection with the help of the provided Datasource and JdbcTemplate class has provided the following methods to execute SQL Queries. 1)For Non Select sql queries and DML SQL queries

public int update(String query) 2)For DDL Sql Queries

public void execute(String query) 3)For Select sql queries

public int queryForInt(String query) public int queryForLong(String query) public String queryForString(String query) public Object queryForObject(String query) public List query(String query) public List queryForList(String query) public Map queryForMap(String query) public RowSet queryForRowSet(String query)

While performing retrival operations to convert data from ResultSet object[records] to Bean objects Spring Framework has provided a predefined interface in the form of "org.springframework.jdbc.core.RowMapper" which contains the following method .

public Object mapRow(ResultSet rs, int rowCount)

Example

Example29
JCode Cell
1 
2package com.durgasoft.dao;
3import org.springframework.jdbc.core.JdbcTemplate;
4import com.durgasoft.beans.Student;
5public interface StudentDao {
6 
7 public void setJdbcTemplate(JdbcTemplate jdbcTemplate);
8 public String add(Student std);
9 public Student search(String sid);
10 public String update(Student std);
11 public String delete(String sid);
12}
13

Ans — StudentDaoImpl.java

Example30
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import org.springframework.jdbc.core.JdbcTemplate;
5 
6import com.durgasoft.beans.Student;
7 
8public class StudentDaoImpl implements StudentDao {
9 private JdbcTemplate jdbcTemplate;
10 String status = "";
11 
12@Override
13public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
14 
15 this.jdbcTemplate = jdbcTemplate ;
16 
17}
18@Override
19public String add(Student std) {
20 
21 try {
22 jdbcTemplate.update("insert into student
23 
24values('"+std.getSid()+"','"+std.getSname()+"','"+std.getSaddr()+"')");
25 status = "success";
26 
27}catch(Exception e) {
28 status = "failure";
29 e.printStackTrace();
30 
31}
32 
33 return status;
34}
35 
36@Override
37public Student search(String sid) {
38 
39 Student std = null;
40 try {
41 std = jdbcTemplate.queryForObject("select * from student where
42sid='"+sid+"'", new StudentMapper());
43 } catch (Exception e) {
44 e.printStackTrace();
45 }
46 return std;
47 }
48 
49 @Override
50 public String update(Student std) {
51 
52 try {
53 jdbcTemplate.update("update student set
54 
55sname='"+std.getSname()+"',saddr='"+std.getSaddr()+"' where sid='"+std.getSid()+"'");
56 status="success";
57 jdbcTemplate.qu
58 
59 }catch(Exception e) {
60 status="failure";
61 e.printStackTrace();
62 
63 }
64 return status;
65 }
66 
67 @Override
68 public String delete(String sid) {
69 
70 try {
71 jdbcTemplate.update("delete from student where sid='"+sid+"'");
72 status="success";
73 
74 } catch (Exception e) {
75 status="failure";
76 e.printStackTrace();
77 
78 }
79 return status;
80 }
81}
82

Ans — Student.java

Example31
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Student {
5 private String sid;
6 private String sname;
7 private String saddr;
8 
9 setXXX() and getXXX()
10 
11}
12

Ans — StudentMapper.java

Example32
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import java.sql.ResultSet;
5import java.sql.SQLException;
6 
7import org.springframework.jdbc.core.RowMapper;
8 
9import com.durgasoft.beans.Student;
10 
11public class StudentMapper implements RowMapper<Student> {
12@Override
13public Student mapRow(ResultSet rs, int row_No) throws SQLException {
14 
15 Student std = new Student();
16 std.setSid(rs.getString("SID"));
17 std.setSname(rs.getString("SNAME"));
18 std.setSaddr(rs.getString("SADDR"));
19 return std;
20 
21}
22}
23

Ans — Test.java

Example33
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import org.springframework.context.support.ClassPathXmlApplicationContext;
6 
7import com.durgasoft.beans.Student;
8import com.durgasoft.dao.StudentDao;
9 
10public class Test {
11 
12 public static void main(String[] args)throws Exception {
13ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
14 
15 StudentDao dao = (StudentDao) context.getBean("studentDao");
16 //----Inserting Records------
17 Student std = new Student();
18 std.setSid("S-111");
19 std.setSname("Durga");
20 std.setSaddr("Hyd");
21 String status = dao.add(std);
22 System.out.println("Student Insertion :"+status);
23 
24std.setSid("S-222");
25std.setSname("Anil");
26std.setSaddr("Hyd");
27status = dao.add(std);
28System.out.println("Student Insertion :"+status);
29 
30std.setSid("S-333");
31std.setSname("Sekhar");
32std.setSaddr("Hyd");
33status = dao.add(std);
34System.out.println("Student Insertion :"+status);
35System.out.println();
36 
37//----Retriving Record-----
38Student std1 = dao.search("S-111");
39if(std1 == null) {
40 
41 System.out.println("Student Search Status :NotExisted");
42}else {
43 
44 System.out.println("Student Details");
45 System.out.println("--------------------");
46 System.out.println("Student Id :"+std1.getSid());
47 System.out.println("Student Name :"+std1.getSname());
48 System.out.println("Student Address :"+std1.getSaddr());
49}
50 System.out.println();
51 
52//----Updating a Record------
53std.setSid("S-111");
54std.setSname("XXX");
55std.setSaddr("YYY");
56status = dao.update(std);
57System.out.println("Student Updation :"+status);
58System.out.println();
59 //----Deleting a record-----
60 status = dao.delete("S-111");
61 System.out.println("Student Deletion :"+status);
62 }
63}
64

Ans — StudentDao.java

In Spring JDBC Applications, we will use positional parameters[?] also in sql queries which we are providing along with JdbcTemplate class provided query execution methods.

If we provide positional parameters in sql queries then JdbcTemplate class will use "PreparedStatement" internally to execute sql query instead of Statement.

To provide values to the Positional parameters in SQL Queries we have to use Object[] with values as parametyer to all JdbcTemplate class provided query execution methods.

public int update(String query, Object[] param_Values) public int queryForInt(String query, Object[] param_Values) public long queryForLong(String query, Object[] param_Values) public Object queryForObject(String query, Object[] param_Values, RowMapper rm) ----- ----- -----

Ex:

String query = "insert into student values(?,?,?)"; int rowCount = jdbcTemplate.update(query, new Object[]{"S-111", "AAA", "Hyd"});

Example:

Example34
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import org.springframework.jdbc.core.JdbcTemplate;
5 
6import com.durgasoft.beans.Student;
7 
8public interface StudentDao {
9 public void setJdbcTemplate(JdbcTemplate jdbcTemplate);
10 public String add(Student std);
11 public Student search(String sid);
12 public String update(Student std);
13 public String delete(String sid);
14 
15}
16

Ans — StudentDaoImpl.java

Example35
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import org.springframework.jdbc.core.JdbcTemplate;
5 
6import com.durgasoft.beans.Student;
7 
8public class StudentDaoImpl implements StudentDao {
9 private JdbcTemplate jdbcTemplate;
10 String status = "";
11 
12@Override
13public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
14 
15 this.jdbcTemplate = jdbcTemplate ;
16 
17}
18@Override
19public String add(Student std) {
20 
21 try { String query = "insert into student values(?,?,?)";
22std.getSaddr()}); jdbcTemplate.update(query, new Object[] {std.getSid(), std.getSname(),
23 
24 status = "success";
25 
26}catch(Exception e) {
27 status = "failure";
28 e.printStackTrace();
29 
30}
31 
32 return status;
33}
34 
35@Override
36public Student search(String sid) {
37 Student std = null;
38 try {
39 
40 std = jdbcTemplate.queryForObject("select * from student where sid=?", new
41Object[] {sid}, new StudentMapper());
42 
43 } catch (Exception e) {
44 e.printStackTrace();
45 
46 }
47 return std;
48 }
49 
50 @Override
51 public String update(Student std) {
52 
53 try {
54 jdbcTemplate.update("update student set sname=?, saddr=? where
55 
56sid=?",new Object[] { std.getSname(), std.getSaddr(), std.getSid()});
57 status="success";
58 
59 }catch(Exception e) {
60 status="failure";
61 e.printStackTrace();
62 
63 }
64 return status;
65}
66 
67 @Override
68 public String delete(String sid) {
69 
70 try {
71 jdbcTemplate.update("delete from student where sid=?", new Object[] {sid});
72 status="success";
73 
74 } catch (Exception e) {
75 status="failure";
76 e.printStackTrace();
77 
78 }
79 return status;
80 }
81}
82

Ans — applicationContext.xml

Example36
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4 
5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6 xmlns:context="http://www.springframework.org/schema/context"
7 xsi:schemaLocation="
8 
9 http://www.springframework.org/schema/beans
10 http://www.springframework.org/schema/beans/spring-beans.xsd
11 http://www.springframework.org/schema/context
12 http://www.springframework.org/schema/context/spring-context.xsd">
13 
14 <bean id="studentDao" class="com.durgasoft.dao.StudentDaoImpl">
15 <property name="jdbcTemplate" ref="jdbcTemplate"/>
16 
17 </bean>
18 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
19 <property name="dataSource" ref="dataSource"/>
20 </bean>
21 
22 <bean id="dataSource"
23class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
24 
25 <property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
26 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
27 <property name="username" value="system"/>
28 <property name="password" value="durga"/>
29 </bean>
30 
31</beans>
32

Ans — StudentMapper.java

Example37
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import java.sql.ResultSet;
5import java.sql.SQLException;
6 
7import org.springframework.jdbc.core.RowMapper;
8 
9import com.durgasoft.beans.Student;
10 
11public class StudentMapper implements RowMapper<Student> {
12@Override
13public Student mapRow(ResultSet rs, int row_No) throws SQLException {
14 
15 Student std = new Student();
16 std.setSid(rs.getString("SID"));
17 std.setSname(rs.getString("SNAME"));
18 std.setSaddr(rs.getString("SADDR"));
19 return std;
20 
21}
22}
23

Ans — Test.java

Example38
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import org.springframework.context.support.ClassPathXmlApplicationContext;
6 
7import com.durgasoft.beans.Student;
8import com.durgasoft.dao.StudentDao;
9 
10public class Test {
11 
12 public static void main(String[] args)throws Exception {
13 ApplicationContext context = new
14 
15ClassPathXmlApplicationContext("applicationContext.xml");
16 StudentDao dao = (StudentDao) context.getBean("studentDao");
17 //----Inserting Records------
18 Student std = new Student();
19 std.setSid("S-111");
20 std.setSname("Durga");
21 std.setSaddr("Hyd");
22 String status = dao.add(std);
23 System.out.println("Student Insertion :"+status);
24 
25 std.setSid("S-222");
26 std.setSname("Anil");
27 std.setSaddr("Hyd");
28 status = dao.add(std);
29 System.out.println("Student Insertion :"+status);
30 
31 std.setSid("S-333");
32 std.setSname("Sekhar");
33 std.setSaddr("Hyd");
34 status = dao.add(std);
35 System.out.println("Student Insertion :"+status);
36 System.out.println();
37 
38 //----Retriving Record-----
39 Student std1 = dao.search("S-111");
40 if(std1 == null) {
41 
42 System.out.println("Student Search Status :NotExisted");
43 }else {
44 
45 System.out.println("Student Details");
46 System.out.println("--------------------");
47 System.out.println("Student Id :"+std1.getSid());
48 System.out.println("Student Name :"+std1.getSname());
49 System.out.println("Student Address :"+std1.getSaddr());
50 }
51 System.out.println();
52 
53 //----Updating a Record------
54 std.setSid("S-111");
55 std.setSname("XXX");
56 std.setSaddr("YYY");
57 status = dao.update(std);
58 System.out.println("Student Updation :"+status);
59 System.out.println();
60 
61 //----Deleting a record-----
62 status = dao.delete("S-111");
63 System.out.println("Student Deletion :"+status);
64 }
65 
66}
67 
68NamedParameterJdbcTemplate
69

Ans — CustomerDao.java

NamedParameterJdbcTemplate class is same as JdbcTemplate class , but, NamedParameterJdbcTemplate class is able to define and run sql queries with Named Parameters instead of positional parameters.

EX:

String query = "insert into student values(:sid, :sname, :saddr)";

Where :sid, :sname, :saddr are named parameters for which we have to provide values.

In case of NamedParameterJdbcTemplate , we are able to provide values to the named parameters in the following two approaches.

  • By Using Map directly.
  • By using SqlParameterSource interface.
  • By Using Map directly.

String query = "insert into student values(:sid, :sname, :saddr)"; Map map = new HashMap(); map.put("sid", "S-111"); map.put("sname", "AAA"); map.put("saddr", "Hyd"); namedParameterJdbcTemplate.update(query, map);

  • By using SqlParameterSource interface.

To provide values to the Named parameters Spring has provided the following two implementation classes for SqlParameterSoure interface.

a)MapSqlParameterSource b)BeanPropertySqlParameterSource

To provide values to the named parameters if we want to use MapSqlParameterSource then first we have to create object for MapSqlParameterSource and we have to use the following method to add values to the named parameters.

public MapSqlParameterSource addValue(String name, Object val)

EX:

String query = "insert into student values(:sid, :sname, :saddr)"; SqlParameterSource param_Source = new MapSqlParameterSource("sid", "S-111"); param_Source = param_Source.addValue("sname", "AAA"); param_Source = param_Source.addValue("saddr", "Hyd"); namedParameterJdbcTemplate.update(query, param_Source);

To provide values to the named parameters if we want to use BeanPropertySqlParameterSource then first we have to create bean object with data then we have to create Object for BeanPropertySqlParameterSource with the generated Bean reference then provide BeanPropertySqlParameterSource object to query methods.

EX:

String query = "insert into student values(:sid, :sname, :saddr)"; Student std = new Student(); std.setSid("S-111"); std.setSname("AAA"); std.setSaddr("Hyd"); SqlParameterSource param_Source = new BeanPropertySqlParameterSource(std ); namedParameterJdbcTemplate.update(query, param_Source);

Note: JdbcTemplate is allowing DataSource object injection through setter method, but, NamedParameterJdbcTemplate class is allowing DataSource object injection through Constructor Dependency Injection.

Example

Example39
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import com.durgasoft.beans.Customer;
5 
6public interface CustomerDao {
7 
8 public String add(Customer c);
9 public Customer search(String cid);
10 public String update(Customer c);
11 public String delete(String cid);
12}
13

Ans — CustomerDaoImpl.java

Example40
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import java.util.HashMap;
5import java.util.Map;
6 
7import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
8import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
9import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
10import org.springframework.jdbc.core.namedparam.SqlParameterSource;
11import org.springframework.jdbc.datasource.DriverManagerDataSource;
12 
13import com.durgasoft.beans.Customer;
14 
15public class CustomerDaoImpl implements CustomerDao {
16 String status = "";
17 private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
18 public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate
19 
20namedParameterJdbcTemplate) {
21 this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
22}
23@Override
24public String add(Customer c) {
25 String query = "insert into customer values(:cid, :cname, :caddr)";
26 Map<String, Object> map = new HashMap<String, Object>();
27 map.put("cid", c.getCid());
28 map.put("cname", c.getCname());
29 map.put("caddr", c.getCaddr());
30 namedParameterJdbcTemplate.update(query, map);
31 return "SUCCESS";
32}
33 
34@Override
35public Customer search(String cid) {
36 
37 String query = "select * from customer where cid=:cid";
38 
39Map<String, Object> map = new HashMap<String, Object>();
40map.put("cid", cid);
41//SqlParameterSource paramSource = new MapSqlParameterSource("cid", cid);
42 
43 Customer c = namedParameterJdbcTemplate.queryForObject(query, map, new
44CustomerMapper());
45 
46 return c;
47}
48 
49 @Override
50 public String update(Customer c) {
51 
52 String query = "update customer set CNAME=:cname, CADDR=:caddr where
53CID=:cid";
54 
55 SqlParameterSource paramSource = new BeanPropertySqlParameterSource(c);
56 namedParameterJdbcTemplate.update(query, paramSource);
57 
58 return "SUCCESS";
59}
60@Override
61public String delete(String cid) {
62 
63 String query = "delete from customer where cid=:cid";
64 SqlParameterSource paramSource = new MapSqlParameterSource("cid", cid);
65 namedParameterJdbcTemplate.update(query, paramSource);
66 return "SUCCESS";
67}
68}
69

Ans — Customer.java

Example41
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Customer {
5 private String cid;
6 private String cname;
7 private String caddr;
8 
9 public String getCid() {
10 return cid;
11 
12 }
13 public void setCid(String cid) {
14 
15 this.cid = cid;
16 }
17 public String getCname() {
18 
19 return cname;
20 }
21 public void setCname(String cname) {
22 
23 this.cname = cname;
24 }
25 public String getCaddr() {
26 
27 return caddr;
28 }
29 public void setCaddr(String caddr) {
30 
31 this.caddr = caddr;
32 }
33 
34}
35

Ans — CustomerMapper.java

Example42
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import java.sql.ResultSet;
5import java.sql.SQLException;
6 
7import org.springframework.jdbc.core.RowMapper;
8 
9import com.durgasoft.beans.Customer;
10 
11public class CustomerMapper implements RowMapper<Customer> {
12@Override
13public Customer mapRow(ResultSet rs, int row_No) throws SQLException {
14 
15 Customer c = new Customer();
16 c.setCid(rs.getString("CID"));
17 c.setCname(rs.getString("CNAME"));
18 c.setCaddr(rs.getString("CADDR"));
19 return c;
20 
21 }
22}
23

Ans — applicationContext.xml

Example43
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4 
5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6 xmlns:context="http://www.springframework.org/schema/context"
7 xsi:schemaLocation="
8 
9 http://www.springframework.org/schema/beans
10 http://www.springframework.org/schema/beans/spring-beans.xsd
11 http://www.springframework.org/schema/context
12 http://www.springframework.org/schema/context/spring-context.xsd">
13 
14 <bean id="customerDao" class="com.durgasoft.dao.CustomerDaoImpl">
15 <property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"/>
16 
17 </bean>
18 <bean id="namedParameterJdbcTemplate"
19 
20class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
21 <constructor-arg ref="dataSource"/>
22 
23 </bean>
24 <bean id="dataSource"
25class="org.springframework.jdbc.datasource.DriverManagerDataSource">
26 
27 <property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
28 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
29 <property name="username" value="system"/>
30 <property name="password" value="durga"/>
31 </bean>
32 
33</beans>
34

Ans — Test.java

Example44
JCode Cell
1 
2package com.durgasoft.test;
3import org.springframework.context.ApplicationContext;
4import org.springframework.context.support.ClassPathXmlApplicationContext;
5 
6import com.durgasoft.beans.Customer;
7import com.durgasoft.dao.CustomerDao;
8 
9public class Test {
10 
11 public static void main(String[] args)throws Exception {
12 ApplicationContext context = new
13 
14ClassPathXmlApplicationContext("applicationContext.xml");
15 CustomerDao dao = (CustomerDao)context.getBean("customerDao");
16 Customer c = new Customer();
17 c.setCid("C-111");
18 c.setCname("AAA");
19 c.setCaddr("Hyd");
20 String status = dao.add(c);
21 System.out.println("Student Insertion :"+status);
22 
23 Customer c1 = dao.search("C-111");
24 System.out.println("Customer Details");
25 System.out.println("--------------------");
26 System.out.println("Customer Id :"+c1.getCid());
27 System.out.println("Customer Name :"+c1.getCname());
28 System.out.println("Customer Address :"+c1.getCaddr());
29 System.out.println();
30 Customer c2 = new Customer();
31 c2.setCid("C-111");
32 c2.setCname("BBB");
33 c2.setCaddr("Sec");
34 status = dao.update(c2);
35 System.out.println("Student Updation Status :"+status);
36 Customer c3 = dao.search("C-111");
37 System.out.println("Customer Updated Details");
38 System.out.println("--------------------");
39 System.out.println("Customer Id :"+c3.getCid());
40 System.out.println("Customer Name :"+c3.getCname());
41 System.out.println("Customer Address :"+c3.getCaddr());
42 System.out.println();
43 status = dao.delete("C-111");
44 System.out.println("Student Deletion Status :"+status);
45}
46}
47

SimpleJdbcTemplate — EmployeeDao.java

In Spring JDBC module, the main intention of SimpleJdbcTemplate class is to provide support for JDK5.0 version feratures like Auto Boxing, Auto Unboxing, Var-Arg methods,.....

SimpleJdbcTemplate class was provided in Spring2.5 version only and it was deprecated in the later versions Spring3.x and Spring4.x , in Spring5.x version SimpleJdbcTemplate class was removed.

If we want to use SimpleJdbcTemplate class we have to use Spring2.5 version jar files in Spring applications.

To execute SQL queries , SimpleJdbcTemplate class has provided the following methods.

public Object execute(String sqlQuery) Note: To use this method we have to get JdbcOperations class by using getJdbcOperations() method.

public int update(String query, Object ... params) public Object queryForInt(String query, Object ... params) public Object queryForLong(String query, Object ... params) public Object query(String query, Object ... params) public Object queryForObject(String query,Object ... params) ---- ---- Note: In case of SimpleJdbcTemplate class, to perform retrival operations, we have to use "ParameterizedRowMapper" inplace of RowMapper interface.

Example:

Example45
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import com.durgasoft.beans.Employee;
5 
6public interface EmployeeDao {
7 public String add(Employee emp);
8 public Employee search(int eno);
9 public String update(Employee emp);
10 public String delete(int eno);
11}
12

SimpleJdbcTemplate — EmployeeDaoImpl.java

Example46
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
5 
6import com.durgasoft.beans.Employee;
7 
8public class EmployeeDaoImpl implements EmployeeDao{
9 private SimpleJdbcTemplate simpleJdbcTemplate;
10 
11String status = "";
12public void setSimpleJdbcTemplate(SimpleJdbcTemplate simpleJdbcTemplate) {
13 
14 this.simpleJdbcTemplate = simpleJdbcTemplate;
15 
16 }
17 @Override
18 public String add(Employee emp) {
19 
20 String query = "insert into emp1
21values("+emp.getEno()+",'"+emp.getEname()+"',"+emp.getEsal()+",'"+emp.getEaddr()+"')";
22 
23 simpleJdbcTemplate.getJdbcOperations().execute(query);
24 status = "SUCCESS";
25 return status;
26 }
27 @Override
28 public Employee search(int eno) {
29 String query = "select * from emp1 where eno=?";
30 Employee emp = simpleJdbcTemplate.queryForObject(query, new
31EmployeeMapper(), eno);
32 
33 return emp;
34 }
35 @Override
36 public String update(Employee emp) {
37 
38 String query = "update emp1 set ename=?, esal =?, eaddr=? where eno=?";
39 simpleJdbcTemplate.update(query, emp.getEname(), emp.getEsal(),
40emp.getEaddr(), emp.getEno());
41 status = "SUCCESS";
42 return status;
43 }
44 @Override
45public String delete(int eno) {
46 String query = "delete from emp1 where eno = ?";
47 simpleJdbcTemplate.update(query, eno);
48 status = "SUCCESS";
49 
50 return status;
51 }
52}
53

SimpleJdbcTemplate — Employee.java

Example47
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Employee {
5 private int eno;
6 private String ename;
7 private float esal;
8 private String eaddr;
9 
10public int getEno() {
11 return eno;
12 
13}
14public void setEno(int eno) {
15 
16 this.eno = eno;
17}
18public String getEname() {
19 
20 return ename;
21}
22public void setEname(String ename) {
23 
24 this.ename = ename;
25}
26public float getEsal() {
27 
28 return esal;
29}
30public void setEsal(float esal) {
31 
32 this.esal = esal;
33}
34public String getEaddr() {
35 
36 return eaddr;
37}
38public void setEaddr(String eaddr) {
39 
40 this.eaddr = eaddr;
41}
42}
43

SimpleJdbcTemplate — EmployeeMapper.java

Example48
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import java.sql.ResultSet;
5import java.sql.SQLException;
6 
7import org.springframework.jdbc.core.RowMapper;
8import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
9 
10import com.durgasoft.beans.Employee;
11 
12public class EmployeeMapper implements ParameterizedRowMapper<Employee> {
13@Override
14public Employee mapRow(ResultSet rs, int row_No) throws SQLException {
15 
16 Employee emp = new Employee();
17 emp.setEno(rs.getInt("ENO"));
18 emp.setEname(rs.getString("ENAME"));
19 emp.setEsal(rs.getFloat("ESAL"));
20 emp.setEaddr(rs.getString("EADDR"));
21 return emp;
22 
23 }
24}
25

SimpleJdbcTemplate — applicationContext.xml

Example49
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4 
5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6 xmlns:context="http://www.springframework.org/schema/context"
7 xsi:schemaLocation="
8 
9 http://www.springframework.org/schema/beans
10 http://www.springframework.org/schema/beans/spring-beans.xsd
11 http://www.springframework.org/schema/context
12 http://www.springframework.org/schema/context/spring-context.xsd">
13 
14<bean id="employeeDao" class="com.durgasoft.dao.EmployeeDaoImpl">
15 <property name="simpleJdbcTemplate" ref="simpleJdbcTemplate"/>
16 
17</bean>
18 <bean id="simpleJdbcTemplate"
19class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
20 
21 <constructor-arg ref="dataSource"/>
22 </bean>
23 <bean id="dataSource"
24class="org.springframework.jdbc.datasource.DriverManagerDataSource">
25 <property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
26 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
27 <property name="username" value="system"/>
28 <property name="password" value="durga"/>
29 </bean>
30 
31</beans>
32

SimpleJdbcTemplate — Test.java

Example50
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import org.springframework.context.support.ClassPathXmlApplicationContext;
6 
7import com.durgasoft.beans.Employee;
8import com.durgasoft.dao.EmployeeDao;
9 
10public class Test {
11 
12 public static void main(String[] args)throws Exception {
13 ApplicationContext context = new
14 
15ClassPathXmlApplicationContext("applicationContext.xml");
16 EmployeeDao dao = (EmployeeDao)context.getBean("employeeDao");
17 Employee emp = new Employee();
18 emp.setEno(111);
19 emp.setEname("AAA");
20 emp.setEsal(5000);
21 emp.setEaddr("Hyd");
22 String status1 = dao.add(emp);
23 System.out.println("Employee Insertion Status :"+status1);
24 System.out.println();
25 Employee emp1 = dao.search(111);
26 System.out.println("Employee Details");
27 System.out.println("--------------------");
28 System.out.println("Employee Number :"+emp1.getEno());
29 System.out.println("Employee Name :"+emp1.getEname());
30 System.out.println("Employee Salary :"+emp1.getEsal());
31 System.out.println("Employee Address :"+emp1.getEaddr());
32 System.out.println();
33 Employee emp2 = new Employee();
34 emp2.setEno(111);
35 emp2.setEname("BBB");
36 emp2.setEsal(6000);
37 emp2.setEaddr("Sec");
38 String status2 = dao.update(emp2);
39 System.out.println("Employee Updation Status :"+status2);
40 System.out.println();
41 String status3 = dao.delete(111);
42 System.out.println("Employee Deletion Status :"+status3);
43 }
44}
45

DAO Support Classes

In Spring JDBC , we have to prepare DAO implementation classes with XXXTemplate property and the corresponding setXXX() method inorder to inject XXXTemplate class.

In Spring JDBC applications, if we want to get XXXTemplate classes with out declaring Template properties and corresponding setXXX() methods we have to use DAO Support classes provided Spring JDBC module.

There are three types of DAOSupport classes inorder to get Template object in DAO classes.

  • JdbcDaoSupport
  • NamedParameterJdbcDaoSupport
  • SimpleJdbcDaoSupport

Where JdbcDaoSupport class will provide JdbcTemplate reference in DAO classes by using the following method.

public JdbcTemplate getJdbcTemplate()

Where NamesParameterJdbcDaoSupport class will provide NamedParameterJdbcTempate reference in DAO classes by using the following method.

public NamedParameterJdbcTemplate getNamedparameterJdbctemplate() Where SimpleJdbcDaoSupport class is able to provide SimpleJdbctemplate reference in Dao class by using the following method.

public SimpleJdbcTemplate getSimpleJdbcTemplate()

EX:

public class EmployeeDaoImpl extends JdbcDaoSupport implements EmployeeDao{

public String insert(int eno, String ename, float esal, String eaddr){ getJdbcTemplate().update("insert into emp1 values("+eno+",'"+ename+"',"+esal+",'"+eaddr+"')"); return "SUCCESS"; } ---- ---- }

Batch Processing — Employee.java

To perform Batch Updations in Spring JDBC we have to use the following method from JdbcTemplate class.

public int[] batchUpdate(String sql_prepared_Statement, BatchPreparedStatementSetter setter)

Where BatchPreparedStatementSetter interface contains the following two methods public void setValues(PreparedStatement ps, int index) public int getBatchSize()

Where setValues() method will be executed for each and every record to set values to the positional parameters existed in PreparedStatement object by getting values from the provided List.

Example52
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Employee {
5 private int eno;
6 private String ename;
7 private float esal;
8 private String eaddr;
9 
10 public int getEno() {
11 return eno;
12 
13 }
14 public void setEno(int eno) {
15 
16 this.eno = eno;
17 }
18 public String getEname() {
19 
20 return ename;
21 }
22 public void setEname(String ename) {
23 
24 this.ename = ename;
25 }
26 public float getEsal() {
27 
28 return esal;
29 }
30 public void setEsal(float esal) {
31 
32 this.esal = esal;
33 }
34 public String getEaddr() {
35 
36 return eaddr;
37 }
38 public void setEaddr(String eaddr) {
39 
40 this.eaddr = eaddr;
41 }
42 
43}
44

Batch Processing — EmployeeDao.java

Example53
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import java.util.List;
5 
6import com.durgasoft.beans.Employee;
7 
8public interface EmployeeDao {
9 public int[] insert(List<Employee> list);
10}
11

Batch Processing — EmployeeDaoImpl.java

Example54
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import java.sql.PreparedStatement;
5import java.sql.SQLException;
6import java.util.List;
7 
8import javax.sql.DataSource;
9 
10import org.springframework.jdbc.core.BatchPreparedStatementSetter;
11import org.springframework.jdbc.core.JdbcTemplate;
12 
13import com.durgasoft.beans.Employee;
14 
15public class EmployeeDaoImpl implements EmployeeDao{
16 private DataSource dataSource;
17 JdbcTemplate jdbcTemplate;
18 public void setDataSource(DataSource dataSource) {
19 this.dataSource = dataSource;
20 jdbcTemplate = new JdbcTemplate(dataSource);
21 }
22 @Override
23 public int[] insert(List<Employee> list) {
24 int[] rowCounts = null;
25 try {
26 String sql = "insert into emp1 values(?,?,?,?)";
27 rowCounts = jdbcTemplate.batchUpdate(sql, new
28 
29BatchPreparedStatementSetter() {
30 @Override
31 public void setValues(PreparedStatement ps, int i) throws
32 
33SQLException {
34 ps.setInt(1, list.get(i).getEno());
35 ps.setString(2, list.get(i).getEname());
36 ps.setFloat(3, list.get(i).getEsal());
37 ps.setString(4, list.get(i).getEaddr());
38 
39 }
40 @Override
41 public int getBatchSize() {
42

Batch Processing

// TODO Auto-generated method stub return list.size(); } }); } catch (Exception e) { e.printStackTrace(); } return rowCounts; } }

Jdbc.properties — applicationContext.xml

jdbc.driverClassName = oracle.jdbc.OracleDriver jdbc.url = jdbc:oracle:thin:@localhost:1521:xe jdbc.username = system jdbc.password = durga

Example56
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4 
5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6 xmlns:context="http://www.springframework.org/schema/context"
7 xsi:schemaLocation="
8 
9 http://www.springframework.org/schema/beans
10 http://www.springframework.org/schema/beans/spring-beans.xsd
11 http://www.springframework.org/schema/context
12 http://www.springframework.org/schema/context/spring-context.xsd">
13 
14<bean id="empDao" class="com.durgasoft.dao.EmployeeDaoImpl">
15 <property name="dataSource" ref="dataSource"/>
16 
17</bean>
18 
19 <bean id="dataSource"
20class="org.springframework.jdbc.datasource.DriverManagerDataSource">
21 
22 <property name="driverClassName" value="${jdbc.driverClassName}"/>
23 <property name="url" value="${jdbc.url}"/>
24 <property name="username" value="${jdbc.username}"/>
25 <property name="password" value="${jdbc.password}"/>
26 </bean>
27 
28<context:property-placeholder location="jdbc.properties"/>
29</beans>
30

Jdbc.properties — Test.java

Example57
JCode Cell
1 
2package com.durgasoft.test;
3 
4import java.util.ArrayList;
5import java.util.List;
6 
7import org.springframework.context.ApplicationContext;
8import org.springframework.context.support.ClassPathXmlApplicationContext;
9 
10import com.durgasoft.beans.Employee;
11import com.durgasoft.dao.EmployeeDao;
12 
13public class Test {
14 
15 public static void main(String[] args) {
16 ApplicationContext context = new
17 
18ClassPathXmlApplicationContext("applicationContext.xml");
19 EmployeeDao dao = (EmployeeDao)context.getBean("empDao");
20 List<Employee> list = new ArrayList<Employee>();
21 Employee e1 = new Employee();
22 e1.setEno(111);
23 e1.setEname("AAA");
24 e1.setEsal(5000);
25 e1.setEaddr("Hyd");
26 list.add(e1);
27 Employee e2 = new Employee();
28 e2.setEno(222);
29 e2.setEname("BBB");
30 e2.setEsal(6000);
31 e2.setEaddr("Hyd");
32 list.add(e2);
33 Employee e3 = new Employee();
34 e3.setEno(333);
35 e3.setEname("CCC");
36 e3.setEsal(6000);
37 e3.setEaddr("Hyd");
38 list.add(e3);
39 
40 int[] rowCounts = dao.insert(list);
41 for(int i = 0; i<rowCounts.length; i++) {
42 System.out.println(rowCounts[i]);
43 
44 }
45 
46 }
47}
48

Stored Procedure and Functions in Spring JDBC

If we want to access stored procedures and functions ehich are available at database from Spring Jdbc application then we have to use "SimpleJdbcCall".

To use SimpleJdbcCall in Spring Jdbc applications we have to use the following steps. 1)Create DAO interface and its implementation class. 2)IN DAO implementation class, we have to declare DataSource and JdbcTemplate and its respective setter method . 3)In side setter method we have to create SimpleJdbcCall object.

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(); jdbcCall.withProcedureName("proc_Name"); 4)Configure DataSource and DAO implementation class in beans configuration file. 5)Access "execute" method by passing IN type parameters values in the form of "SQLParameterSource". public Map execute(Map m) pubhlic Map execute(SqlParameterSource paramSource) public Map execute(Object ... obj)

Procedure to copy at Database — Employee.java

create or replace procedure getSalary(no IN number, sal OUT int) AS BEGIN select esal into sal from emp1 where eno = no; END getSalary; /

Example59
JCode Cell
1 
2package com.durgasoft.beans;
3public class Employee {
4private int eno;
5private String ename;
6private float esal;
7private String eaddr;
8 
9public int getEno() {
10return eno;
11}
12public void setEno(int eno) {
13this.eno = eno;
14}
15public String getEname() {
16return ename;
17}
18public void setEname(String ename) {
19this.ename = ename;
20}
21public float getEsal() {
22return esal;
23}
24public void setEsal(float esal) {
25this.esal = esal;
26}
27public String getEaddr() {
28return eaddr;
29}
30public void setEaddr(String eaddr) {
31this.eaddr = eaddr;
32}
33 
34}
35

Procedure to copy at Database — EmployeeDao.java

Example60
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import java.util.Map;
5 
6import com.durgasoft.beans.Employee;
7 
8public interface EmployeeDao {
9public void create(Employee emp);
10public Object getEmployeeSalary(int eno);
11}
12

Procedure to copy at Database — EmployeeDaoImpl.java

Example61
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import java.util.Map;
5 
6import javax.sql.DataSource;
7 
8import org.springframework.jdbc.core.JdbcTemplate;
9import
10org.springframework.jdbc.core.namedparam.MapSqlParameterSourc
11e;
12import
13org.springframework.jdbc.core.namedparam.SqlParameterSource;
14import org.springframework.jdbc.core.simple.SimpleJdbcCall;
15 
16import com.durgasoft.beans.Employee;
17 
18public class EmployeeDaoImpl implements EmployeeDao {
19private DataSource dataSource;
20private SimpleJdbcCall jdbcCall;
21public void setDataSource(DataSource dataSource) {
22this.dataSource = dataSource;
23jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("getSalary");
24 
25}
26@Override
27public void create(Employee emp) {
28try {
29JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
30String sql= "insert into emp1 values("+emp.getEno()+",'"+emp.getEname()+"',"+emp.getEsal()+"
31,'"+emp.getEaddr()+"')";
32jdbcTemplate.update(sql);
33}catch(Exception e) {
34e.printStackTrace();
35}
36 
37}
38@Override
39public Object getEmployeeSalary(int eno) {
40SqlParameterSource in = new MapSqlParameterSource().addValue("no", eno);
41Map<String, Object> map = jdbcCall.execute(in);
42 
43// System.out.println(map);
44return map.get("SAL");
45}
46}
47

Procedure to copy at Database — applicationContext.xml

Example62
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8http://www.springframework.org/schema/beans
9http://www.springframework.org/schema/beans/spring-
10beans.xsd
11http://www.springframework.org/schema/context
12 
13http://www.springframework.org/schema/context/spring-
14context.xsd">
15<bean id="empDao" class="com.durgasoft.dao.EmployeeDaoImpl">
16<property name="dataSource" ref="dataSource"/>
17</bean>
18<bean id = "dataSource" class =
19"org.springframework.jdbc.datasource.DriverManagerDataSource">
20<property name = "driverClassName" value = "oracle.jdbc.OracleDriver"/>
21<property name = "url" value = "jdbc:oracle:thin:@localhost:1521:xe"/>
22<property name = "username" value = "system"/>
23<property name = "password" value = "durga"/>
24</bean>
25</beans>
26

Procedure to copy at Database — Test.java

Example63
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import
6org.springframework.context.support.ClassPathXmlApplicationCo
7ntext;
8 
9import com.durgasoft.beans.Employee;
10import com.durgasoft.dao.EmployeeDao;
11 
12public class Test {
13 
14public static void main(String[] args)throws
15Exception {
16ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
17EmployeeDao dao = (EmployeeDao)context.getBean("empDao");
18 
19Employee emp1 = new Employee();
20emp1.setEno(111);
21emp1.setEname("AAA");
22emp1.setEsal(5000);
23emp1.setEaddr("Hyd");
24dao.create(emp1);
25Object salary1 = dao.getEmployeeSalary(emp1.getEno());
26System.out.println(emp1.getEno()+"---->"+salary1);
27 
28Employee emp2 = new Employee();
29emp2.setEno(222);
30emp2.setEname("BBB");
31emp2.setEsal(6000);
32emp2.setEaddr("Hyd");
33dao.create(emp2);
34Object salary2 = dao.getEmployeeSalary(emp2.getEno());
35System.out.println(emp2.getEno()+"---->"+salary2);
36 
37Employee emp3 = new Employee();
38emp3.setEno(333);
39emp3.setEname("CCC");
40emp3.setEsal(7000);
41emp3.setEaddr("Hyd");
42dao.create(emp3);
43Object salary3 = dao.getEmployeeSalary(emp3.getEno());
44System.out.println(emp3.getEno()+"---->"+salary3);
45 
46}
47}
48

Procedure from Spring JDBC Application by using SimpleJdbcCall

If we want to use CURSOR types in Stored Procedures inorder to retrive multiple Records data then we have to use the following method on SimpleJdbcCall reference.

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource) jdbcCall = jdbcCall.withProcedureName("getAllEmployees"); jdbcCall = jdbcCall.returningResultSet("emps",BeanPropertyRowMapper.newInstance(Employee.class));

After adding returningResultSet(--,--) method, if we access execute() method on SimpleJdbcCall then execute() method will execute procedure, it will get all the results from CURSOR type variable and stored all recordfs in the form of Employee objects in an ArrayList object with "emps"[CURSOR TYPE variable] key in a Map.

Example:

COPY this Procedure in Database — Employee.java

create or replace procedure getAllEmployees(emps OUT SYS_REFCURSOR) AS BEGIN open emps for select * from emp1; END getAllEmployees; /

Example65
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Employee {
5private int eno;
6private String ename;
7private float esal;
8private String eaddr;
9public int getEno() {
10return eno;
11}
12public void setEno(int eno) {
13this.eno = eno;
14}
15public String getEname() {
16return ename;
17}
18public void setEname(String ename) {
19this.ename = ename;
20}
21public float getEsal() {
22return esal;
23}
24public void setEsal(float esal) {
25this.esal = esal;
26}
27public String getEaddr() {
28return eaddr;
29}
30public void setEaddr(String eaddr) {
31this.eaddr = eaddr;
32}
33 
34}
35

COPY this Procedure in Database — EmployeeDao.java

Example66
JCode Cell
1 
2package com.durgasoft.dao;
3import java.util.Map;
4public interface EmployeeDao {
5public Map<String, Object> getAllEmployees();
6}
7

COPY this Procedure in Database — EmployeeDaoImpl.java

Example67
JCode Cell
1 
2package com.durgasoft.dao;
3import java.util.Map;
4 
5import javax.sql.DataSource;
6 
7import org.springframework.jdbc.core.BeanPropertyRowMapper;
8import org.springframework.jdbc.core.simple.SimpleJdbcCall;
9 
10import com.durgasoft.beans.Employee;
11 
12public class EmployeeDaoImpl implements EmployeeDao {
13private SimpleJdbcCall jdbcCall;
14private DataSource dataSource;
15public void setDataSource(DataSource dataSource) {
16this.dataSource = dataSource;
17jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("getAllEmployees");
18jdbcCall = jdbcCall.returningResultSet("emps",
19BeanPropertyRowMapper.newInstance(Employee.class));
20}
21@Override
22public Map<String, Object> getAllEmployees() {
23 
24Map<String, Object> map = jdbcCall.execute();
25 
26//System.out.println(map);
27return map;
28}
29}
30

COPY this Procedure in Database — applicationContext.xml

Example68
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:context="http://www.springframework.org/schema/context"
6xsi:schemaLocation="
7http://www.springframework.org/schema/beans
8http://www.springframework.org/schema/beans/spring-beans.xsd
9http://www.springframework.org/schema/context
10http://www.springframework.org/s…/context/spring-context.xsd">
11<bean id="empDao" class="com.durgasoft.dao.EmployeeDaoImpl">
12<property name="dataSource" ref="dataSource"/>
13</bean>
14<bean id = "dataSource"
15class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
16<property name = "driverClassName" value = "oracle.jdbc.OracleDriver"/>
17<property name = "url" value = "jdbc:oracle:thin:@localhost:1521:xe"/>
18<property name = "username" value = "system"/>
19<property name = "password" value = "durga"/>
20</bean>
21</beans>
22

COPY this Procedure in Database — Test.java

Example69
JCode Cell
1 
2package com.durgasoft.test;
3 
4import java.util.ArrayList;
5import java.util.Map;
6 
7import org.springframework.context.ApplicationContext;
8import org.springframework.context.support.ClassPathXmlApplicationContext;
9 
10import com.durgasoft.beans.Employee;
11import com.durgasoft.dao.EmployeeDao;
12 
13public class Test {
14 
15public static void main(String[] args)throws Exception {
16ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
17EmployeeDao dao = (EmployeeDao)context.getBean("empDao");
18Map<String, Object> map = dao.getAllEmployees();
19System.out.println(map);
20ArrayList<Employee> list =(ArrayList<Employee>) map.get("emps");
21System.out.println(list);
22 
23System.out.println("Employee Details");
24System.out.println("ENO\tENAME\tESAL\tEADDR");
25System.out.println("-----------------------------");
26for(Employee e: list) {
27System.out.println(e.getEno()+"\t"+e.getEname()+"\t"+e.getEsal()+"\t"+e.getEaddr());
28}
29 
30}
31 
32}
33

Blob and Clob processing in Spring JDBC

BLOB: It is a data type available at Databases to represent large volumes of binary data. CLOB: It is a data type available at Database to represent large volumes of character data.

In Spring JDBC Applications, to process BLOB and CLOB Data, Spring JDBC has provided the following three interfaces mainly.

AbstractLobCreatingPreparedStatementCallback

--> It will be used to store Blob and Clob related data in Database.

protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException, DataAccessException

AbstractLobStreamingResultSetExtractor

--> It will be used to retrive BLOB and CLOB data from database.

streamData(ResultSet rs)throws SQLException, IOException, DataAccessException

LobCreator

--> It contains the following methods to prepare Binary stream and character streams to send blob and clob data to database.

setBlobAsBinaryStream() setClobAsCharacterStream()

LobHolder — Employee.java

--> It contains the following methods to get Binary stream and character stream to get blob and clob data.

getBlobAsBinaryStream() getClobAsCharacterStream()

Example:

Example74
JCode Cell
1 
2package com.durgasoft.beans;
3 
4import java.io.File;
5 
6public class Employee {
7 private int eno;
8 private String ename;
9 private File emp_Image;
10 private File emp_Resume;
11 
12 public int getEno() {
13 return eno;
14 
15 }
16 public void setEno(int eno) {
17 
18 this.eno = eno;
19 }
20 public String getEname() {
21 
22 return ename;
23 }
24 public void setEname(String ename) {
25 
26 this.ename = ename;
27 }
28 public File getEmp_Image() {
29 
30 return emp_Image;
31 }
32 public void setEmp_Image(File emp_Image) {
33 
34 this.emp_Image = emp_Image;
35 }
36 public File getEmp_Resume() {
37 
38 return emp_Resume;
39 }
40 public void setEmp_Resume(File emp_Resume) {
41 
42 this.emp_Resume = emp_Resume;
43 }
44}
45

LobHolder — EmployeeDao.java

Example75
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import com.durgasoft.beans.Employee;
5 
6public interface EmployeeDao {
7 public void insertEmployee(Employee emp);
8 public Employee readEmployee();
9 
10}
11

LobHolder — EmployeeDaoImpl.java

Example76
JCode Cell
1 
2package com.durgasoft.dao;
3import java.io.File;
4import java.io.FileInputStream;
5import java.io.FileOutputStream;
6import java.io.FileReader;
7import java.io.FileWriter;
8import java.io.IOException;
9import java.sql.PreparedStatement;
10import java.sql.ResultSet;
11import java.sql.SQLException;
12 
13import javax.sql.DataSource;
14 
15import org.springframework.dao.DataAccessException;
16import org.springframework.jdbc.core.JdbcTemplate;
17import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback;
18import org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor;
19import org.springframework.jdbc.support.lob.LobCreator;
20import org.springframework.jdbc.support.lob.LobHandler;
21import org.springframework.util.FileCopyUtils;
22 
23import com.durgasoft.beans.Employee;
24 
25public class EmployeeDaoImpl implements EmployeeDao {
26 private LobHandler lobHolder;
27 private DataSource dataSource;
28 private JdbcTemplate jdbcTemplate;
29 
30 public void setDataSource(DataSource dataSource) {
31 this.dataSource = dataSource;
32 jdbcTemplate = new JdbcTemplate(dataSource);
33 
34 }
35 public void setLobHolder(LobHandler lobHolder) {
36 
37 this.lobHolder = lobHolder;
38 }
39 public LobHandler getLobHolder() {
40 
41 return lobHolder;
42 }
43 @Override
44 public void insertEmployee(Employee emp) {
45 
46 String sql_Query = "insert into emp10 values(?,?,?,?)";
47 jdbcTemplate.execute(sql_Query, new
48AbstractLobCreatingPreparedStatementCallback(lobHolder) {
49 @Override
50 protected void setValues(PreparedStatement ps, LobCreator lobCreator)
51throws SQLException, DataAccessException {
52 
53 FileInputStream fis = null;
54 FileReader fr = null;
55 try {
56 
57 ps.setInt(1, emp.getEno());
58 ps.setString(2, emp.getEname());
59 fis = new FileInputStream(emp.getEmp_Image());
60 fr = new FileReader(emp.getEmp_Resume());
61 lobCreator.setBlobAsBinaryStream(ps, 3, fis,
62(int)emp.getEmp_Image().length());
63 lobCreator.setClobAsCharacterStream(ps, 4, fr,
64(int)emp.getEmp_Resume().length());
65 }catch(IOException e) {
66 e.printStackTrace();
67 }
68 }
69 } );
70 
71}
72 
73@Override
74public Employee readEmployee() {
75 
76 Employee emp = new Employee();
77 
78 String sql = "select * from emp10";
79 jdbcTemplate.query(sql, new
80AbstractLobStreamingResultSetExtractor<Object>() {
81 
82 @Override
83 protected void streamData(ResultSet rs) throws SQLException,
84IOException, DataAccessException {
85 
86 emp.setEno(rs.getInt(1));
87 emp.setEname(rs.getString(2));
88 
89 File file1 = new File("E:/spring/my_image.jpg");
90 FileOutputStream fos = new FileOutputStream(file1);
91 FileCopyUtils.copy(lobHolder.getBlobAsBinaryStream(rs, 3), fos);
92 emp.setEmp_Image(file1);
93 
94 File file2 = new File("E:/spring/my_resume.docx");
95 FileWriter fw = new FileWriter(file2);
96 FileCopyUtils.copy(lobHolder.getClobAsCharacterStream(rs, 4), fw);
97 emp.setEmp_Resume(file2);
98 
99 }
100 });
101 
102 return emp;
103 }
104 
105}
106

LobHolder — applicationContext.xml

Example77
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4 
5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6 xmlns:context="http://www.springframework.org/schema/context"
7 xsi:schemaLocation="
8 
9 http://www.springframework.org/schema/beans
10 http://www.springframework.org/schema/beans/spring-beans.xsd
11 http://www.springframework.org/schema/context
12 http://www.springframework.org/schema/context/spring-context.xsd">
13 
14 <bean id="empDao" class="com.durgasoft.dao.EmployeeDaoImpl">
15 <property name="dataSource" ref="dataSource"/>
16 <property name="lobHolder" ref="lobHolder"/>
17 
18 </bean>
19 
20 <bean id="dataSource"
21class="org.springframework.jdbc.datasource.DriverManagerDataSource">
22 
23 <property name="driverClassName" value="${jdbc.driverClassName}"/>
24 <property name="url" value="${jdbc.url}"/>
25 <property name="username" value="${jdbc.username}"/>
26 <property name="password" value="${jdbc.password}"/>
27 </bean>
28 <bean id="lobHolder" class="org.springframework.jdbc.support.lob.DefaultLobHandler">
29 </bean>
30 <context:property-placeholder location="jdbc.properties"/>
31 
32</beans>
33

jdbc.properties — Test.java

jdbc.driverClassName = oracle.jdbc.OracleDriver jdbc.url = jdbc:oracle:thin:@localhost:1521:xe jdbc.username = system jdbc.password = durga

Example78
JCode Cell
1 
2package com.durgasoft.test;
3 
4import java.io.File;
5 
6import org.springframework.context.ApplicationContext;
7import org.springframework.context.support.ClassPathXmlApplicationContext;
8 
9import com.durgasoft.beans.Employee;
10import com.durgasoft.dao.EmployeeDao;
11 
12public class Test {
13 
14 public static void main(String[] args)throws Exception {
15 ApplicationContext context = new
16 
17ClassPathXmlApplicationContext("applicationContext.xml");
18 EmployeeDao dao = (EmployeeDao)context.getBean("empDao");
19 File file1 = new File("E:/spring/nag.jpg");
20 File file2 = new File("E:/spring/nag_resume.docx");
21 Employee emp1 = new Employee();
22 emp1.setEno(111);
23 emp1.setEname("Nag");
24 emp1.setEmp_Image(file1);
25 emp1.setEmp_Resume(file2);
26 dao.insertEmployee(emp1);
27 System.out.println("Employee Inserted Successfully");
28 
29 Employee emp2 = dao.readEmployee();
30 System.out.println("Employee Retrived Successfully");
31 System.out.println("Employee Details");
32 System.out.println("---------------------");
33 System.out.println("Employee Number :"+emp2.getEno());
34 System.out.println("Employee Name :"+emp2.getEname());
35 System.out.println("Employee Image :"+emp2.getEmp_Image().getAbsolutePath());
36 System.out.println("Employee Resume
37:"+emp2.getEmp_Resume().getAbsolutePath());
38 }
39}
40

Spring JDBC Connection Pooling Mechanism

In Database related applications, if we want to perform database operations first we have to creater Connection object then we have to close connection object when the database operations are completed. IN Database related applications, every time creating Connection object and every time destroying Connection object may reduce application performance, because, Creating Connection object and destroying Connection object are two expensive processes, which may reduce application performance.

To overcome the above problem we have to use Connection Pooling in applications.In Connection pooling we will create a set of Connection object in the form of a pool at the application startup time and we will reuse that COnnection objects while executing applications , when database operations are completed then we will send back that connection objects to Pool object with out destroying that connection objects.

In SPring JDBC applications there are three approaches to provide connection pooling.

  • Default Connection Pooling Mech.
  • Third Party Connection Pooling Mechanisms
  • Application Servers provided Connection Pooling Mechanism
  • Default Connection Pooling Mech.

In SPring Framework, Default Connection pooling mechanism is existed in the form of org.springframework.jdbc.datasource.DriverManagerDataSource, it is usefull upto testging only, it is usefull for production environment of the application.

If we want to use default Connection Pooling mechanism in SPring JDBC application then we have to configure org.springframework.jdbc.datasource.DriverManagerDataSource in beans configuration file with the following properties .

  • driverClassName
  • url
  • username
  • password

EX:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/> <property name="username" value="system"/> <property name="password" value="durga"/> </bean>

Third Party Connection Pooling Mechanisms

In Spring JDBC applications we are able to use the following third party connection pooling mechanisms

  • Apache DBCP
  • C3P0
  • Proxool

Apache DBCP

To use Apcahes DBCP connection pooling mechanism then we have to configure org.apache.commons.dbcp2.BasicDataSource class with the following properties in spring beans configuration file.

  • driverClassName
  • url
  • username
  • password
  • initialSize:It will take Initial pool size.
  • maxTotal: It will allow the specified no of max connections.

EX:

--- <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">

<property name="driverClassName" value="oracle.jdbc.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" /> <property name="username" value="root" /> <property name="password" value="root" /> <property name="initialSize" value="20" /> <property name="maxTotal" value="30" /> </bean>

Note: To use this mechanism in Spring JDBC Applications then we have to add the following two jar files to Library.

  • commons-dbcp2-2.2.0.jar
  • commons-pool2-2.5.0.jar

C3P0 — Employee.java

To use C3P0 connection pooling mechanism then we have to configure com.mchange.v2.c3p0.ComboPooledDataSource class with the following properties in spring beans configuration file.

  • driverClass
  • jdbcUrl
  • user
  • password
  • minPoolSize:It will take Initial pool size.
  • maxPoolSize: It will allow the specified no of max connections.
  • maxStatements: Max statements it allows.
  • testConnectionOnCheckOut:true/false for Checking Connection before use.

EX:

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="oracle.jdbc.OracleDriver" /> <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe" /> <property name="user" value="system" /> <property name="password" value="durga" /> <property name="maxPoolSize" value="30" /> <property name="minPoolSize" value="10" /> <property name="maxStatements" value="100" /> <property name="testConnectionOnCheckout" value="true" />
</bean>

Note: To use this mechanism in Spring JDBC Applications then we have to add the following two jar files to Library.

  • c3p0-0.9.5.2.jar
  • mchange-commons-java-0.2.11.jar
  • Proxool:

To use Proxool connection pooling mechanism then we have to configure org.logicalcobwebs.proxool.ProxoolDataSource class with the following properties in spring beans configuration file.

  • driver
  • driverUrl
  • user
  • password
  • minimumConnectionCount:It will take Initial pool size.
  • maximumConnectionCount: It will allow the specified no of max connections.

EX:

<bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"> <property name="driver" value="oracle.jdbc.OracleDriver" /> <property name="driverUrl" value="jdbc:oracle:thin:@localhost:1521:xe" /> <property name="user" value="system" /> <property name="password" value="durga" /> <property name="maximumConnectionCount" value="30" /> <property name="minimumConnectionCount" value="10" />
</bean>

Note: To use this mechanism in Spring JDBC Applications then we have to add the following two jar files to Library.

  • proxool-0.9.1.jar
  • proxool-cglib.jar

Example:

Example82
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Employee {
5 private int eno;
6 private String ename;
7 private float esal;
8 private String eaddr;
9 
10public int getEno() {
11 return eno;
12 
13}
14public void setEno(int eno) {
15 
16 this.eno = eno;
17}
18public String getEname() {
19 
20 return ename;
21}
22public void setEname(String ename) {
23 this.ename = ename;
24 }
25 public void setEsal(float esal) {
26 
27 this.esal = esal;
28 }
29 public float getEsal() {
30 
31 return esal;
32 }
33 public void setEaddr(String eaddr) {
34 
35 this.eaddr = eaddr;
36 }
37 public String getEaddr() {
38 
39 return eaddr;
40 }
41}
42

C3P0 — EmployeeDao.java

Example83
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import com.durgasoft.beans.Employee;
5 
6public interface EmployeeDao {
7 public void insertEmployee(Employee emp);
8 
9}
10

C3P0 — EmployeeDaoImpl.java

Example84
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import javax.sql.DataSource;
5 
6import org.springframework.jdbc.core.JdbcTemplate;
7 
8import com.durgasoft.beans.Employee;
9 
10public class EmployeeDaoImpl implements EmployeeDao {
11 private DataSource dataSource;
12 private JdbcTemplate jdbcTemplate;
13 
14public void setDataSource(DataSource dataSource) {
15 this.dataSource = dataSource;
16 jdbcTemplate = new JdbcTemplate(dataSource);
17 }
18 @Override
19 public void insertEmployee(Employee emp) {
20 String sql_Query = "insert into emp1
21values("+emp.getEno()+",'"+emp.getEname()+"',"+emp.getEsal()+",'"+emp.getEaddr()+"')";
22 jdbcTemplate.execute(sql_Query);
23 
24 }
25}
26

C3P0 — applicationContext.xml

Example85
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4 
5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6 xmlns:context="http://www.springframework.org/schema/context"
7 xsi:schemaLocation="
8 
9 http://www.springframework.org/schema/beans
10 http://www.springframework.org/schema/beans/spring-beans.xsd
11 http://www.springframework.org/schema/context
12 http://www.springframework.org/schema/context/spring-context.xsd">
13 
14 <bean id="empDao" class="com.durgasoft.dao.EmployeeDaoImpl">
15 <property name="dataSource" ref="dataSource"/>
16 
17 </bean>
18<!-- Default Connection Pooling Mechanism
19<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
20 
21 <property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
22 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
23 <property name="username" value="system"/>
24 <property name="password" value="durga"/>
25</bean>
26-->
27<!-- DBCP Connection Pooling Mechanism Properties
28 <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
29 
30 <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
31 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
32 <property name="username" value="system" />
33 <property name="password" value="durga" />
34 <property name="initialSize" value="20" />
35 <property name="maxTotal" value="30" />
36 </bean>
37-->
38<!-- C3P0 Connection Pooling Mechanism Properties
39<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
40 <property name="driverClass" value="oracle.jdbc.OracleDriver" />
41 <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe" />
42 <property name="user" value="system" />
43 <property name="password" value="durga" />
44 <property name="maxPoolSize" value="30" />
45 <property name="minPoolSize" value="10" />
46 <property name="maxStatements" value="100" />
47 <property name="testConnectionOnCheckout" value="true" />
48</bean>
49-->
50<!-- Proxool Connection Pooling Mechanism Properties -->
51<bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">
52 <property name="driver" value="oracle.jdbc.OracleDriver" />
53 <property name="driverUrl" value="jdbc:oracle:thin:@localhost:1521:xe" />
54 <property name="user" value="system" />
55 <property name="password" value="durga" />
56 <property name="maximumConnectionCount" value="30" />
57 <property name="minimumConnectionCount" value="10" />
58</bean>
59</beans>
60

C3P0 — Test.java

Example86
JCode Cell
1 
2package com.durgasoft.test;
3import org.springframework.context.ApplicationContext;
4import org.springframework.context.support.ClassPathXmlApplicationContext;
5import com.durgasoft.beans.Employee;
6import com.durgasoft.dao.EmployeeDao;
7public class Test {
8 
9 public static void main(String[] args)throws Exception {
10 ApplicationContext context = new
11 
12ClassPathXmlApplicationContext("applicationContext.xml");
13 EmployeeDao dao = (EmployeeDao)context.getBean("empDao");
14 Employee emp = new Employee();
15 emp.setEno(111);
16 emp.setEname("Nag");
17 emp.setEsal(5000);
18 emp.setEaddr("Hyd");
19 dao.insertEmployee(emp);
20 System.out.println("Employee Inserted Successfully");
21 
22 }
23}
24

Application Servers provided Connection Pooling Mechanism throw JNDI

JNDI[Java Naming And Directory Interface]: JNDI is a Middleware Service or an abstraction provided by SUN Micreosystems as part of J2EE and which is implemented by all the Application Servers vendors like Weblogic, JBOSS, Glassfish,.....

JNDI is existed inside the application Servers to provide any resource with Global Scope, that is, JNDI will share any resource like "DataSource" to all the applications which are running in the present application server.

In general, almost all the Application Servers are having their own Connection Pooling mechanisms, if we want to use Application Servers provided Connection pooling mechanisms we have to use the following steps.

1)Install Application Server. 2)COnfigure Connection Pooling and Datasource in JNDI provided by Application Servers. 3)Add the required new JARs to Library. 4)Provide JNDI Setups in beans configuration File.

1) Install Application Server[Weblogic Server]

  • Download fmw_12.2.1.3.0_wls_quick.jar from internet[oracle.com]
  • Open command prompt in Administrator mode.
  • Set JAVA8 or JAVA7 in path.

set path=C:\Java\jdk1.8.0_144\bin;

  • Goto setup file loaction and execute JAR file with the following command.

F:\softwares\servers\weblogic>java -jar fmw_12.2.1.3.0_wls_quick.jar

  • Click on "Next" button.
  • Click on "Next" Button
  • Specify Home directory "Oracle"
  • Click on "Next" button.
  • Click on "Next" button.
  • Click on "Next" button
  • Click on "Install" button.
  • Click on "Next" button.
  • Click on "Finish" button.
  • Provide domain name "durga_domain".
  • Click on "Next" button.
  • Click on "Next" button.
  • Provide user name and password.

user name: weblogic password: weblogic_weblogic confirm password: weblogic_weblogic

  • Click on "Next" button.
  • Click on "Next" button.
  • Select "Adminstration Server"
  • CLick on "Next" button.
  • Click on "Next" button.
  • Click on "Create" button.
  • Click on "Next" button.
  • Click on "Finish" button.

COnfigure Connection Pooling and Datasource in JNDI provided by Application Servers

  • Goto durga_domain location

C:\Oracle\user_projects\domains\durga_domain

  • double click on "startWeblogic" batch file.
  • Open Browser and provide the following url to open Administration console.

http://localhost:7001/console

  • Provide domain user name and password.

user name: weblogic password: weblogic_weblogic

  • Click on "Login" button.
  • Go for Domain Structer and select "Services".
  • Select "DataSource".
  • Click on "New" button.
  • Select "Generic datasource".
  • Provide the following details.

Name: durgads Scope: GLOBAL JNDI Name: durgajndi Database Type: Oracle

  • Click on "Next" button.
  • Click on "Next" button.
  • Click on "Next" button.
  • Provide the following details.

Database Name: xe Host Name: localhost Port : 1521 Database User Name: system password: durga confirm password: durga

  • Click on "Next" button.
  • Click on "Next" button.
  • Select "admin server".
  • Click on "Finish" button.

Add the required new JARs to Library

To use Weblogic Server provided Connection Pooling mechanism in Spring JDBC Application then we have to use the following jars along with the regular jars. 1)weblogic.jar 2)spring-jdbc-4.0.4.RELEASE.jar 3)spring-tx-4.0.4.RELEASE.jar

Provide JNDI Setups in beans configure — Employee.java

To use Weblogic Server provided Connection Pooling mechanism in Spring JDBC Application then we have to provide the following DataSource configuration in beans configuration file.\

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="durgajndi"/> <property name="jndiEnvironment">
<props> <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop> <prop key="java.naming.provider.url">t3://localhost:7001</prop>
</props> </property>
</bean>
<bean id="empDao" class="com.durgasoft.dao.EmployeeDaoImpl"> <property name="dataSource" ref="dataSource"/>
</bean>

Example:

Example90
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Employee {
5 private int eno;
6 private String ename;
7 private float esal;
8 private String eaddr;
9 
10 public int getEno() {
11 return eno;
12 
13 }
14 public void setEno(int eno) {
15 
16 this.eno = eno;
17 }
18 public String getEname() {
19 
20 return ename;
21 }
22 public void setEname(String ename) {
23 
24 this.ename = ename;
25 }
26 public void setEsal(float esal) {
27 
28 this.esal = esal;
29 }
30 public float getEsal() {
31 
32 return esal;
33 }
34 public void setEaddr(String eaddr) {
35 
36 this.eaddr = eaddr;
37 }
38 public String getEaddr() {
39 
40 return eaddr;
41 }
42}
43

Provide JNDI Setups in beans configure — EmployeeDao.java

Example91
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import com.durgasoft.beans.Employee;
5 
6public interface EmployeeDao {
7 public void insertEmployee(Employee emp);
8 
9}
10

Provide JNDI Setups in beans configure — EmployeeDaoImpl.java

Example92
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import javax.sql.DataSource;
5 
6import org.springframework.jdbc.core.JdbcTemplate;
7 
8import com.durgasoft.beans.Employee;
9 
10public class EmployeeDaoImpl implements EmployeeDao {
11 private DataSource dataSource;
12 private JdbcTemplate jdbcTemplate;
13 
14 public void setDataSource(DataSource dataSource) {
15 this.dataSource = dataSource;
16 jdbcTemplate = new JdbcTemplate(dataSource);
17 
18 }
19 @Override
20 public void insertEmployee(Employee emp) {
21 
22 String sql_Query = "insert into emp1
23values("+emp.getEno()+",'"+emp.getEname()+"',"+emp.getEsal()+",'"+emp.getEaddr()+"')";
24 
25 jdbcTemplate.execute(sql_Query);
26 
27 }
28}
29

Provide JNDI Setups in beans configure — applicationContext.xml

Example93
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4 
5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6 xmlns:context="http://www.springframework.org/schema/context"
7 xsi:schemaLocation="
8 
9 http://www.springframework.org/schema/beans
10 http://www.springframework.org/schema/beans/spring-beans.xsd
11 http://www.springframework.org/schema/context
12 http://www.springframework.org/schema/context/spring-context.xsd">
13 
14<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
15 <property name="jndiName" value="durgajndi"/>
16 <property name="jndiEnvironment">
17 <props>
18 
19 <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
20 <prop key="java.naming.provider.url">t3://localhost:7001</prop>
21 </props>
22 </property>
23 </bean>
24 
25 <bean id="empDao" class="com.durgasoft.dao.EmployeeDaoImpl">
26 <property name="dataSource" ref="dataSource"/>
27 
28 </bean>
29 
30</beans>
31

Provide JNDI Setups in beans configure — Test.java

Example94
JCode Cell
1 
2package com.durgasoft.test;
3import org.springframework.context.ApplicationContext;
4import org.springframework.context.support.ClassPathXmlApplicationContext;
5import org.springframework.remoting.rmi.JndiRmiProxyFactoryBean;
6 
7import com.durgasoft.beans.Employee;
8import com.durgasoft.dao.EmployeeDao;
9 
10public class Test {
11 
12 public static void main(String[] args)throws Exception {
13 
14 ApplicationContext context = new
15ClassPathXmlApplicationContext("applicationContext.xml");
16 
17 EmployeeDao dao = (EmployeeDao)context.getBean("empDao");
18 Employee emp = new Employee();
19 emp.setEno(111);
20 emp.setEname("AAA");
21 emp.setEsal(5000);
22 emp.setEaddr("Hyd");
23 dao.insertEmployee(emp);
24 System.out.println("Employee Inserted Successfully");
25 }
26}
27
📝 Key Takeaways
  • Key ideas of Spring - JDBC / DAO explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end