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!
- Create a Zip file using Java Code programmatically
- Eclipse : A java Runtime Environment (JRE) or Java Development kit (JDK) must be available
- How to Sort a LinkedList in Java
- Loading class com.mysql.jdbc.Driver. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver
- How to declare and initialize Array in Java Programming
- [Fix] java: integer number too large compilation error
- Java JDBC Connection with MySQL Driver in VS Code + Troubleshooting
- Reading .xls and .xlsx Excel file using Apache POI Java Library
- IntelliJ: Error: Could not find or load main class, java.lang.ClassNotFoundException
- How to get Client IP address using Java Code Example
- Truncate table using Java JDBC Example
- Struts 2 : There is no Action mapped for namespace [/] and action name [form] associated with context path [/proj]
- How to get file path in Idea IntelliJ IDE
- Java Generics explained with simple definition and examples
- Java SE 8 Update 301 available with various bug fixes and security improvements
- Java: Collect Stream as ArrayList or LinkedList
- Java JDBC Connection with PostgreSQL Driver Example
- How to check if Java main thread is alive
- How to fix Java nio NoSuchFileException wile reading a file
- Java 8+ get Day of the Week Examples with LocalDateTime, DateTime, ZonalDateTime and Instant classes
- Ways to Convert Integer or int to Long in Java
- [Java] How to throws Exception using Functional Interface and Lambda code
- [Fix] Spring Boot: mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
- Java: The value of the local variable string is not used
- Java JDBC: Insert Java 8 LocalDate and Time using PreparedStatement
- Python Sleep Function/Method Code Example - Python
- Java 8: Steam map with Code Examples - Java
- How to Merge Branch into Master Branch - Git
- Advanced ways to set Custom Settings for a Website on Safari for Mac - MacOS
- fix macOS: The digital signature on the update is missing or invalid. Ventura - MacOS
- Show Desktop Keyboard Shortcut on Mac - MacOS
- Add Line Number before each line in Notepad++ using Column Editor - NotepadPlusPlus
- Android : Class file collision: A resource exists with a different case - Android