Persistence layer technology comparison: what is the difference between Mybatis and JDBC

CSDN Topic Challenge Phase 2
Participating Topic: Java Technology Sharing

Table of contents

I. Introduction

2. Example of using native JDBC

3. Example of using Mybatis

4. The respective usage scenarios of native JDBC and Mybatis

V. Conclusion


 

I. Introduction

The last time I wrote an article was before the Mid-Autumn Festival, and I participated in the Mid-Autumn Festival event of csdn, nearly a month and a half ago. During the period, I picked up the pen several times and wanted to write some words, but I couldn't get interested, and I always felt that I couldn't write well. I thought about it for a long time and decided to learn how to write first. During this period of time, I have read several books on how to write intermittently, and I have roughly mastered some writing methods, so I will write a technical article today to practice my writing. This article will introduce the development methods and usage scenarios of JDBC and Mybatis, help beginners better understand the persistence layer technology, and promote the persistence layer framework such as Mybatis. From now on, assume you are a beginner. After learning JDBC, you will continue to learn persistence layer frameworks such as Mybatis. In the process of learning, we will consider a problem. Now that there is JDBC technology, why is there a persistence layer framework?

 

2. Example of using native JDBC

First of all, we need to know what is JDBC?

JDBC is a specification, a set of interface definitions, which defines how to use the JAVA language to operate the database. Then major database vendors implement this set of interfaces using the Java language, and we can operate the database through the connector in the Java project. The most common one is the Mysql connector. If you are not sure, you can read the article I wrote before: mysql-connector-java detailed explanation .

Next, let's take a look at the usage examples of native JDBC programming, and summarize the shortcomings of only using JDBC programming.

public static void main(String[] args) {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    try {
        //加载数据库驱动
        Class.forName("com.mysql.jdbc.Driver");
        //通过驱动管理类获取数据库链接
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8", "root", "mysql");
        //定义sql语句 ?表示占位符
        String sql = "select * from user where username = ?";
        //获取预处理statement
        preparedStatement = connection.prepareStatement(sql);
        //设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
        preparedStatement.setString(1, "张三");
        //向数据库发出sql执行查询,查询出结果集
        resultSet = preparedStatement.executeQuery();
        //遍历查询结果集
        while (resultSet.next()) {
            System.out.println(resultSet.getString("id") + "  " + resultSet.getString("username"));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //释放资源
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

The above is a programming example of JDBC. Now let's summarize the shortcomings, as shown in the following four points:

1. When creating a connection, closing a connection, and handling exceptions, there are many redundant and repeated codes, resulting in only a small part of the business code in a very long method

2. Sql statements are hard-coded in the code, which is not easy to maintain

3. Sql input parameters need to be mapped by themselves, and the placeholders in sql must be manually processed to match the input parameters with the placeholders

4. When obtaining the data returned by the database, you need to manually create the object, then traverse the result set, and put the data into the object

 

3. Example of using Mybatis

First of all, we need to know what is Mybatis?

Mybatis is a persistence layer framework, which encapsulates the process of JDBC's database operation, so that developers only need to pay attention to Sql itself, without spending energy on processing such as registering drivers, creating connections, creating statements, manually setting parameters, and retrieving results Set and other tedious processes. Mybatis simplifies the development process of native JDBC and makes up for the shortcomings of native JDBC.

Next, let's take a look at an example of using Mybatis programming.

/**
 * 用户实体
 */
public class User {
private int id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
}

/**
 * 用户管理mapper
 */
public interface UserMapper {
//查询用户列表
public List<User> findUserByUsername(String username);
}

 <!-- 映射文件 -->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.mybatis.mapper.UserMapper">
<!-- 查询用户列表 -->
<select id="findUserByUsername" parameterType="java.lang.String" 
resultType="cn.itcast.mybatis.po.User">
   select * from user where username = #{username} 
</select>
</mapper>

/**
 * 用户管理service
 */
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    /**
     * 查询用户列表
     */
    @Override
    public List<User> findUserByUsername(String username){
        return userMapper.findUserByUsername(username);
    }
}
 

The above is an example of using Mybatis to operate the database. In the final service, it can be seen that the operation of the database is very simple, there is no redundant connection creation, connection closure, and exception code handling. The input parameters of sql will be automatically mapped to sql, and the output result set of sql will be automatically mapped to Java objects. Let us focus more on business code without considering code that has nothing to do with business.

 

4. The respective usage scenarios of native JDBC and Mybatis

The usage scenarios for native JDBC are twofold.

On the one hand, when we first started learning Java technology, we will use native JDBC in the project.

On the other hand, native JDBC is used in some very old projects. Due to historical reasons, when developing these old projects, the persistence layer framework has not yet appeared. If these old projects have undergone technical upgrades, they will gradually replace native JDBC with the persistence layer framework.

Overall, Mybatis simplifies the JDBC development process. As beginners, when we learn technology, we must fully understand and learn JDBC well. But in formal projects, in order to develop projects better and faster, persistence frameworks such as Mybatis are generally used.

 

V. Conclusion

Finally, to make a summary, native JDBC is the basis of using the Java language to operate the database. You must study it carefully. Only by mastering the basics can you better learn the framework and understand the principles of the framework.

Only when we understand the shortcomings of using native JDBC to operate the database, can we better appreciate the advantages of persistence layer frameworks such as Mybatis.

Talking about the follow-up plan, I will try to write some serialized and systematic technical articles, and connect the previously written articles from individual points into a line, so that readers can better understand related technologies.

If you have any questions, please leave a message in the comment area, and I will answer them one by one.

 

 

 

 

Guess you like

Origin blog.csdn.net/keyboard_/article/details/127477755