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'}
Facing issues? Have Questions? Post them here! I am happy to answer!
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
- JUnit 4 Setup Example with IntelliJ + Maven - Java
- TextEdit save file with txt extension - MacOS
- Fix: ModuleNotFoundError: No module named pip - PIP
- 7 deadly java.lang.OutOfMemoryError in Java Programming - Java
- Remove Trailing zeros BigDecimal Java - Java
- cURL Option to show HTTP Response Status Code - cURL
- Find Hostname of Mac running on macOS Ventura 13 - MacOS
- How to upload and read csv file in Google Colab - Google