Here comes the MyBatis persistence layer framework

Posted by dsainteclaire on Tue, 04 Jan 2022 00:53:56 +0100

When developing JAVA projects, we need to interact with the database. At the beginning of database programming, we choose JDBC, which is the API for how to interact between the database and JAVA programs, but the steps are cumbersome. Today, we will learn about the latest database framework, MyBatis. It is a semi-automatic persistence layer framework. Why is it semi-automatic? Because it also needs to write SQL statements manually, it is called semi-automatic framework. So what are its advantages over JDBC? Now draw a picture for you to see:

Compared with JDBC, it greatly simplifies the operation steps of the database, but the configuration may be a little troublesome.

1. Important concepts in MyBatis

  • sqlSession

As the name suggests, this is a session. The SqlSession object is not thread safe. In the multi-threaded environment of the server, we should create an independent SqlSession object for each thread. For example:

In a Servlet, every time a new request is received, it can be regarded as a separate thread (the Servlet is executed in a multithreaded environment)
Within each request processing method, a separate SqlSession object needs to be created before operating the database Therefore, the life cycle of the SqlSession object can be regarded as that each request has its own SqlSession

  • sqlSessionFactory
    This object is used to help create SqlSession objects The lifecycle should be consistent with the application.

Do not create SqlSessionFactory multiple times in an application!
You can use singleton mode to manage SqlSessionFactory.

  • Mapper Interface

For example, we create a XXMapper, which is the Mapper interface
1. When creating XXMapper, the SQL statement corresponding to each method is specified through annotation.
2. In the configuration file SqlMapCon "g" XML, and then you can get the specific instance of XXMapper through the getMapper method of SqlSession.
The operation equivalent to manually assembling SQL statements is automatically generated by MyBaits.

2. SQL mapping file

  • create mapping file

    Create the corresponding xml Mapping File

1.property corresponds to the attribute in the entity class, and column corresponds to the field name of the database table;
2. The name in the namespace must be the fully qualified class name of Mapper interface;
3. The id value of select must be consistent with the corresponding method name in Mapper interface;
4. In this configuration, two methods are used for mapping. One is to directly use as to create an alias in SQL, and the other is to use resultMap. The effects of the two methods are the same or can be mixed.

  • Modify profile

Modify SqlMapCon fi g.xml. Other parts remain unchanged. Only the contents in mapper are modified

  • Modify Mapper Interface

Remove the comments, otherwise an error will be reported.

3. MyBatis completes the operation of adding, deleting, querying and modifying
Take StudentMapper as an example:

  1. Modify the StudentMapper interface, add, delete and modify the interface, as follows
public interface StudentMapper{
  List<Student> selectAll();
  StudentselectOne(intstudentId);
  voidinsert(Studentstudent);
  voidupdate(Studentstudent);
  voiddelete(intstudentId);
}

  1. Modify studentmapper XML file

Configure selectOne

<selectid="selectOne"resultMap="studentResultMap"parameterType="int">
 SELECT
 student_id,
 student_name,
 score
 FROM student
 where student_id=#{id}
</select>

Configure insert

<insertid="insert"parameterType="Student">
 INSERT INTO student
 VALUE(#{studentId},#{studentName},#{score});
</insert>

Configure update

<updateid="update"parameterType="Student">
  UPDATE student
  set student_name=#{studentName},score=#{score}
  where student_id=#{studentId};
</update>

Configure delete

<deleteid="delete"parameterType="int">
 DELETE FROM student
 where student_id=#{studentId}
</delete>

Full mapping file

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEmapper
    PUBLIC"-//mybatis.org//DTDMapper3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="StudentMapper">
  <select id="selectAll"resultMap="studentResultMap">
   SELECT
     student_id,
     student_name,
     score
   FROM student
  </select>
  <selectid="selectOne"resultMap="studentResultMap"parameterType="int">
   SELECT
     student_id,
     student_name,
     score
   FROM student
   where student_id=#{id}
  </select>
<insertid="insert"parameterType="Student">
   INSERT INTO student
   VALUE(#{studentId},#{studentName},#{score});
  </insert>
  <updateid="update"parameterType="Student">
   UPDATE student
   set student_name=#{studentName},score=#{score}
   where student_id=#{studentId};
  </update>
  <delete id="delete"parameterType="int">
   DELETE FROM student
   where student_id=#{studentId}
  </delete>
  <resultMapid="studentResultMap"type="Student">
    <resultproperty="studentId"column="student_id"/>
    <resultproperty="studentName"column="student_name"/>
  </resultMap>
</mapper>

The next step is to test. The following is the test code:

public static void main(String[]args){
  try{
    //1. Get the content of the configuration file
    InputStream inputStream=Resources.getResourceAsStream("SqlMapConfig.xml");
    //2. Create SqlSessionFactory object
    SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
    //3. Create SqlSession object
    SqlSessionsql Session=factory.openSession();
    //4. Create StudentMapper object
    StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);
    //5. Execute database operation
    //a) Get all records
    List<Student> studentList=studentMapper.selectAll();
    System.out.println("Get all records:"+studentList);
    //b) Get a single record
    Student student=studentMapper.selectOne(1);
    System.out.println("Get a single record:"+student);
    //c) Insert record
    Student guanzhilin=newStudent();
    guanzhilin.setStudentId(19);
    guanzhilin.setStudentName("Guan Zhilin");
    guanzhilin.setScore(100);
    studentMapper.insert(caixukun);
    studentList=studentMapper.selectAll();
    System.out.println("insert record:"+studentList);
    //d) Update record
    guanzhilin.setScore(200);
    studentMapper.update(guanzhilin);
    guanzhilin=studentMapper.selectOne(guanzhilin.getStudentId());
    System.out.println("Modify record:"+guanzhilin);
    //e) Delete record
    studentMapper.delete(19);
    studentList=studentMapper.selectAll();
    System.out.println("Delete record:"+studentList);
    //6. Close and release resources
    sqlSession.commit();
    sqlSession.close();

4. MyBatis and Hibernate

(1) Are relational databases, persistence layer framework (ORM framework);
(2) MyBatis is a semi-automatic ORM framework, and Hibernate is a fully automatic ORM framework;
(3) MyBatis has the advantage of low learning threshold, which is conducive to sql performance optimization and maintenance. The disadvantage is that it can not cross databases, because the sql statements written by itself may hold the characteristics and keywords of some databases.
(4) Hibernate sql has a higher learning threshold and needs to learn a large number of APIs. Although it does not need handwritten sql, it can write sql statements by calling API, so it can cross databases. It depends heavily on the database model and is difficult to maintain once it is changed.

The above is MyBatis Now many enterprises are developing larger and larger projects, and have higher and higher requirements for the database. The storage of a large amount of data has become a focus issue, and the addition, deletion, query and modification of a large amount of data has also become a focus. Therefore, it is necessary to learn the database well.

Topics: Database MySQL Mybatis