This is a very basic getting started Spring JDBC Template example, you can download the code from GitHub,
GitHub Repo Link: https://github.com/code2care/string-jdbc-template
Prerequisite
- Java 8+
- Gradle
- IDE - Eclipse/IntelliJ/VS Code
- MySQL/Oracle/Postgres DB Connector jar
- Spring Core + Context + JDBC dependencies.
Setting up Gradle Project
Create a Gradle project and add the below in the build.gradle dependencies,
dependencies {
implementation group: 'org.springframework', name: 'spring-context', version: '5.3.22'
implementation group: 'org.springframework', name: 'spring-core', version: '5.3.22'
implementation group: 'org.springframework', name: 'spring-jdbc', version: '5.3.22'
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.30'
}
Based on what database you are using add the connector - in this example, we have used MySQL, you can get all these dependencies strings from https://mvnrepository.com
The Project Structure:

Create the Database Table with some records:
Let's create a simple table student,
CREATE TABLE `student` (
`student_id` int NOT NULL,
`student_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`student_id`));
insert into student values(1, 'Sam');
Create Properties file:
db.propertiesmysql_driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/my_uat
db_user=root
db_pwd=root123
Create Application Config class:
AppConfig.javapackage config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
@Configuration
@ComponentScan("dao")
@PropertySource("classpath:db.properties")
public class AppConfig {
@Autowired
Environment environment;
@Bean
DataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setUrl(environment.getProperty("url"));
driverManagerDataSource.setUsername(environment.getProperty("db_user"));
driverManagerDataSource.setPassword(environment.getProperty("db_pwd"));
driverManagerDataSource.setDriverClassName(environment.getProperty("mysql_driver"));
return driverManagerDataSource;
}
}
Create the Student Pojo and Dao and Dao Impl:
Student.javapackage entities;
public class Student {
private int studentId;
private String studentName;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
@Override
public String toString() {
return "Student{" +
"studentId=" + studentId +
", studentName='" + studentName + '\'' +
'}';
}
}
StudentDao.java
package dao;
import entities.Student;
public interface StudentDao {
Student getStudentById(int studentId);
}
StudentDaoImpl.java
package dao;
import javax.sql.DataSource;
import entities.Student;
import entities.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class StudentDaoImpl implements StudentDao {
JdbcTemplate jdbcTemplate;
@Autowired
public StudentDaoImpl(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public Student getStudentById(int studentId) {
return jdbcTemplate.queryForObject("select * from student where student_id = ?", new Object[] { studentId }, new StudentRowMapper());
}
}
StudentRowMapper.java
package entities;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class StudentRowMapper implements RowMapper<Student> {
public Student mapRow(ResultSet resultSet, int noOfRows) throws SQLException {
Student student = new Student();
student.setStudentId(resultSet.getInt("student_id"));
student.setStudentName(resultSet.getString("student_name"));
return student;
}
}
Testing our Results
SpringJdbcTemplateExample.javaimport config.AppConfig;
import dao.StudentDao;
import entities.Student;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringJdbcTemplateExample {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
StudentDao studentDao = context.getBean(StudentDao.class);
Student student = studentDao.getStudentById(1);
System.out.println(student);
context.close();
}
}
Output:
Student{studentId=1, studentName='Sam'}
-
Have Questions? Post them here!
More Posts related to Java,
- Add two numbers using Java Generics
- Convert Java List to Json String using Jackson
- Convert Java Object to JSON using Jackson Library
- Java SE JDBC: Insert with PreparedStatement Example
- [Program] How to read three different values using Scanner in Java
- Java JDBC Batch Update Example with PreparedStatement
- Java Stream flatmap() Examples
- Save Java Object as JSON file using Jackson Library
- Java get day of the week as an int using DayOfWeek
- Create Nested Directories using Java Code
- Java JDBC Delete a Record in Database Table using PreparedStatement
- List of jars required for Struts2 project
- Convert Java Object to XML using Jackson Library
- Struts2 : java.lang.ClassNotFoundException: org.apache.commons.fileupload.RequestContext
- Java JDBC Get Id of the Inserted Record with AutoIncrement
- How to list all tables using Java JDBC
- Java Jackson ObjectMapper Class with Examples
- Fix: Maven - Failed to execute goal - Compilation failure - Source/Target option 5 is no longer supported. Use 7 or later
- Eclipse : The type java.lang.CharSequence cannot be resolved. Indirectly referenced from required .class files
- Formatting Double in Java [Examples]
- How to run Java Unit Test cases with Apache Maven?
- [fix] NullPointerException Cannot Invoke findById because Repository is null - Java Spring
- [Fix] java: integer number too large compilation error
- [Java] Read a File with UTF-8 Encoding
- How to detect Operating System using Java code
More Posts:
- Program 9: Divide Two Numbers - 1000+ Python Programs - Python-Programs
- How to clear ZSH history of commands executed on Mac Terminal - zsh
- Whats new in Python 3.10 Pre-release - Python
- [Solution] Installing Whatsapp There's insufficient space on the device - WhatsApp
- Loading previous page using html button using JavaScript - JavaScript
- Java equals method - Tutorial - Java
- Sort ls command by last modified date and time - Linux
- Docker Alpine Linux and Apache2 Example - Docker