Spring JdbcTemplate
Spring JdbcTemplate
Problems of JDBC API
The problems of JDBC API are as follows:
- We need to write a lot of code before and after executing the query, such as creating connection, statement, closing resultset, connection etc.
- We need to perform exception handling code on the database logic.
- We need to handle transaction.
- Repetition of all these codes from one to another database logic is a time consuming task.
Spring Jdbc Approaches
- JdbcTemplate
- NamedParameterJdbcTemplate
- SimpleJdbcTemplate
- SimpleJdbcInsert and SimpleJdbcCall
JdbcTemplate class
It is the central class in the Spring JDBC support classes. It takes care of creation and release of resources such as creating and closing of connection object etc. So it will not lead to any problem if you forget to close the connection.
It handles the exception and provides the informative exception messages by the help of excepion classes defined in the org.springframework.dao package.
We can perform all the database operations by the help of JdbcTemplate class such as insertion, updation, deletion and retrieval of the data from the database.
Let's see the methods of spring JdbcTemplate class
No. Method Description
1) public int update(String query) is used to insert, update and delete records.
2) public int update(String query,Object... args) is used to insert, update and delete records using PreparedStatement using given arguments.
3) public void execute(String query) is used to execute DDL query.
4) public T execute(String sql, PreparedStatementCallback action) executes the query by using PreparedStatement callback.
5) public T query(String sql, ResultSetExtractor rse) is used to fetch records using ResultSetExtractor.
6) public List query(String sql, RowMapper rse) is used to fetch records using RowMapper.
Employee.java
This class contains 3 properties with constructors and setter and getters.
package com.spring.jdbc.springjdbc;
public class Employee {
private int id;
private String name;
private float salary;
public Employee() {
super();
// TODO Auto-generated constructor stub
}
public Employee(int id, String name, float salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
EmployeeDao.java
It contains one property jdbcTemplate and three methods saveEmployee(), updateEmployee and deleteEmployee().
package com.spring.jdbc.springjdbc;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int SaveEmployee(Employee employee)
{
String query="insert into employee values ('"+employee.getId()+"','"+employee.getName()+"','"+employee.getSalary()+"')";
return jdbcTemplate.update(query);
}
public int updateEmployee(Employee employee){
String query="update employee set name='"+employee.getName()+"',salary='"+employee.getSalary()+"' where id='"+employee.getId()+"' ";
return jdbcTemplate.update(query);
}
public int deleteEmployee(Employee employee){
String query="delete from employee where id='"+employee.getId()+"' ";
return jdbcTemplate.update(query);
}
}
jdbcConfig.xml
The DriverManagerDataSource is used to contain the information about the database such as driver class name, connnection URL, username and password.
There are a property named datasource in the JdbcTemplate class of DriverManagerDataSource type. So, we need to provide the reference of DriverManagerDataSource object in the JdbcTemplate class for the datasource property.
Here, we are using the JdbcTemplate object in the EmployeeDao class, so we are passing it by the setter method but you can use constructor also.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- JdbcTemplate Configuration
datasource is an interface so it implement from driverclass
jdbctemplate -> datasource -> drivermanager class
-->
<!-- DataSource Configuration for MySQL -->
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" name='ds'>
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/springJdbc" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- JdbcTemplate Configuration -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" name='jdbcTemplate' >
<property name="dataSource" ref="ds" />
</bean>
<bean id="edao" class="com.jdbc.jdbcspring.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
App.java
This class gets the bean from the applicationContext.xml file and calls the saveEmployee() method. You can also call updateEmployee() and deleteEmployee() method by uncommenting the code as well.
package com.jdbc.jdbcspring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
ApplicationContext ctx=new ClassPathXmlApplicationContext("com/jdbc/jdbcspring/jdbcConfig.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
int status=dao.saveEmployee(new Employee(102,"Amit",35000));
System.out.println(status);
/* int status=dao.updateEmployee(new Employee(102,"Sonoo",15000));
System.out.println(status);
int status=dao.saveEmployee(new Employee(102,"Amit",35000));
System.out.println(status);
*/
/*Employee e=new Employee();
e.setId(102);
int status=dao.deleteEmployee(e);
System.out.println(status);*/
}
}
Comments
Post a Comment