There is how MyBatis Eliminates a lot of JDBC boilerplate code

Manish Saini
3 min readFeb 2, 2021

--

Java has a Java DataBase Connectivity (JDBC) API to work with relational databases. But JDBC is a very low-level API, and we need to write a lot of code to perform database operations.

Let us examine how we can implement simple insert and select operations
on a STUDENTS table using plain JDBC.

Assume that the STUDENTS table has STUD_ID , NAME , EMAIL , and DOB columns.
The corresponding Student JavaBean is as follows:

package com.mybatis3.domain;
import java.util.Date;
public class Student {
private Integer studId;
private String name;
private String email;
private Date dob;
// setters and getters
}

The following StudentService.java program implements the SELECT and INSERT
operations on the STUDENTS table using JDBC.

public Student findStudentById(int studId) {
Student student = null;
Connection conn = null;
try{
//obtain connection
conn = getDatabaseConnection();
String sql = “SELECT * FROM STUDENTS WHERE STUD_ID=?”;
//create PreparedStatement
PreparedStatement pstmt = conn.prepareStatement(sql);
//set input parameters
pstmt.setInt(1, studId);
ResultSet rs = pstmt.executeQuery();
//fetch results from database and populate into Java objects
if(rs.next()) {
student = new Student();
student.setStudId(rs.getInt(“stud_id”));
student.setName(rs.getString(“name”));
student.setEmail(rs.getString(“email”));
student.setDob(rs.getDate(“dob”));
}
} catch (SQLException e){
throw new RuntimeException(e);
}finally{
//close connection
if(conn!= null){
try {
conn.close();
} catch (SQLException e){ }
}
}
return student;
}
public void createStudent(Student student) {
Connection conn = null;
try{
//obtain connection
conn = getDatabaseConnection();
String sql = “INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB)
VALUES(?,?,?,?)”;
//create a PreparedStatement
PreparedStatement pstmt = conn.prepareStatement(sql);
//set input parameters
pstmt.setInt(1, student.getStudId());
pstmt.setString(2, student.getName());
pstmt.setString(3, student.getEmail());
pstmt.setDate(4, new
java.sql.Date(student.getDob().getTime()));
pstmt.executeUpdate();
} catch (SQLException e){
throw new RuntimeException(e);
}finally{
//close connection
if(conn!= null){
try {
conn.close();
} catch (SQLException e){ }
}
}
}
protected Connection getDatabaseConnection() throws SQLException {
try{
Class.forName(“com.mysql.jdbc.Driver”);
return DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”, “root”, “admin”);
} catch (SQLException e){
throw e;
} catch (Exception e){
throw new RuntimeException(e);
}
}

There is a lot of duplicate code in each of the preceding methods, for creating
a connection, creating a statement, setting input parameters, and closing the
resources, such as the connection, statement, and result set.

MyBatis abstracts all these common tasks so that the developer can focus on the
really important aspects, such as preparing the SQL statement that needs to be
executed and passing the input data as Java objects.

In addition to this, MyBatis automates the process of setting the query parameters
from the input Java object properties and populates the Java objects with the SQL
query results as well.

Now let us see how we can implement the preceding methods using MyBatis:
1. Configure the queries in a SQL Mapper config file, say StudentMapper.xml .

<select id=”findStudentById” parameterType=”int”
resultType=” Student”>
SELECT STUD_ID AS studId, NAME, EMAIL, DOB
FROM STUDENTS WHERE STUD_ID=#{Id}
</select>
<insert id=”insertStudent” parameterType=”Student”>
INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB)
VALUES(#{studId},#{name},#{email},#{dob})
</insert>

2. Create a StudentMapper interface.

public interface StudentMapper {
Student findStudentById(Integer id);
void insertStudent(Student student);
}

3. In Java code, you can invoke these statements as follows:

SqlSession session = getSqlSessionFactory().openSession();
StudentMapper mapper =
session.getMapper(StudentMapper.class);
// Select Student by Id
Student student = mapper.selectStudentById(1);
//To insert a Student record
mapper.insertStudent(student);

That’s it! You don’t need to create the Connection , PrepareStatement , extract ,
and set parameters and close the connection by yourself for every database
operation. Just configure the database connection properties and SQL statements,
and MyBatis will take care of all the ground work.

Don’t worry about what SqlSessionFactory , SqlSession , and Mapper XML files
are. These concepts will be explained in detail in the coming chapters.

Along with these, MyBatis provides many other features that simplify the
implementation of persistence logic.

• It supports the mapping of complex SQL result set data to nested object
graph structures
• It supports the mapping of one-to-one and one-to-many results
to Java objects
• It supports building dynamic SQL queries based on the input data

--

--