Skip to main content

Spring JbcTemplate mini tutorial

Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC API but eliminates a lot of problems of JDBC API.

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 a connection, statement, closing resultset, connection, etc.
  • We need to perform exception handling code on the database logic.
  • We need to handle the transaction.
  • Repetition of all these codes from one to another database logic is a time-consuming task.

Advantage of Spring JdbcTemplate

Spring JdbcTemplate eliminates all the above-mentioned problems of JDBC API. It provides you methods to write the queries directly, so it saves a lot of work and time.

Spring Jdbc Approaches
Spring framework provides following approaches for JDBC database access:
  • 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 exception classes defined in the org.springframework.daopackage.
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.MethodDescription
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, PreparedStatementCallbackaction)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.

Example of Spring JdbcTemplate

We are assuming that you have created the following table inside the Oracle10g database.
  1. create table employee(  
  2. id number(10),  
  3. name varchar2(100),  
  4. salary number(10)  
  5. );  
Employee.java
This class contains 3 properties with constructors and setter and getters.
  1. package com.javatpoint;  
  2.   
  3. public class Employee {  
  4. private int id;  
  5. private String name;  
  6. private float salary;  
  7. //no-arg and parameterized constructors  
  8. //getters and setters  
  9. }  
EmployeeDao.java
It contains one property jdbcTemplate and three methods saveEmployee(), updateEmployee and deleteEmployee().
  1. package com.javatpoint;  
  2. import org.springframework.jdbc.core.JdbcTemplate;  
  3.   
  4. public class EmployeeDao {  
  5. private JdbcTemplate jdbcTemplate;  
  6.   
  7. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
  8.     this.jdbcTemplate = jdbcTemplate;  
  9. }  
  10.   
  11. public int saveEmployee(Employee e){  
  12.     String query="insert into employee values(  
  13.     '"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";  
  14.     return jdbcTemplate.update(query);  
  15. }  
  16. public int updateEmployee(Employee e){  
  17.     String query="update employee set   
  18.     name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";  
  19.     return jdbcTemplate.update(query);  
  20. }  
  21. public int deleteEmployee(Employee e){  
  22.     String query="delete from employee where id='"+e.getId()+"' ";  
  23.     return jdbcTemplate.update(query);  
  24. }  
  25.   
  26. }  

Comments

Popular posts from this blog

How to secure SpringBoot with SSL and Tomcat or Undertow

when we are going to take our applications to production mode, we must have an SSL certificate for the FrontEnd and   BackEnd too, in this case, our backend is a  SpringBoot which is using a tomcat embedded server. Terminology TLS vs SSL TLS is the successor to SSL. It is a protocol that ensures privacy between communicating applications. Unless otherwise stated, in this document consider TLS and SSL as interchangable. Certificate (cert) The public half of a public/private key pair with some additional metadata about who issued it etc. It may be freely given to anyone. Private Key A private key can verify that its corresponding certificate/public key was used to encrypt data. It is never given out publicly. Certificate Authority (CA) A company that issues digital certificates. For SSL/TLS certificates, there are a small number of providers (e.g. Symantec/Versign/Thawte, Comodo, GoDaddy, LetsEncrypt) whose certificates are included by most browsers and Op...

How to deploy a VueJS App using Nginx on Ubuntu

There are thousands of blogs and websites out there explaining how to do a hello world and how to start with VueJS, but in this little post, I’m just going to be explaining how to do deploy a VueJs app after you have run the command through the CLI npm run build . So when you run the command npm run build a dist folder is created and that folder’s got the essential .js files to run our app, when we want to run our app on an Nginx server by default the vue-router is not going to work well so that Nginx does not come ready to work by default with a VueJs app This is basically for a Linux Ubuntu distribution if you’ve got any other Linux distribution just pay attention where is going to be set the www/html folder and the Nginx settings so that this is useful for any Linux distribution  Install and configure nginx sudo apt install nginx Double check to make sure the nginx service is running with command service nginx status, then open your browser and enter ...

Printing using SpringBoot - cups4j

One of the easiest ways to print something from Java , in this case, using a SpringBoot Java Api Rest is with CUPS . Let's assume you've set up your CUPS server up and running, add to your pom.xml file this dependency      < dependency >      < groupId > org.cups4j </ groupId >      < artifactId > cups4j </ artifactId >      < version > 0.7.6 </ version > </ dependency > now at this imports to import  java.io.FileInputStream; import  java.io.FileNotFoundException; import  java.net.URL; import  java.util.HashMap; import  java.util.List; import  org.cups4j.CupsClient; import  org.cups4j.CupsPrinter; import  org.cups4j.PrintJob; import  org.cups4j.PrintJobAttributes; import  org.cups4j.PrintRequestResult; import  org.cups4j.WhichJobsEnum; add this method to prin...