Configuration and use of MyBatis (add, delete, change, check)

Posted by mcdsoftware on Sun, 13 Oct 2019 08:47:03 +0200

- Restore content to start

Introduction to Mybatis

Introduction to MyBatis

What is MyBtis?

MyBatis is an open source framework that simplifies and implements the Java data persistence layer. It abstracts a lot of JDBC redundant code and provides a simple and easy-to-use API and database interaction.

MyBatis's predecessor was iBATIS, which was founded by Clinton Begin in 2002. MyBatis 3 is a new design for iBATIS, supporting annotations and appers.  

MyBatis is popular mainly because of its simplicity and ease of use. In Java applications, the data persistence layer involves the following tasks: generating the Java objects needed by querying the data from the database; and persisting the data in the Java objects to the database through SQL.

MyBatis makes it easy to use SQL by abstracting the underlying JDBC code and automating the process of generating Java objects and data persistence databases of Java objects from SQL result sets. as

Why choose MyBtis?

  • The most important thing is to eliminate a lot of JDBC redundancy.
  • Learning costs are low
  • He can work well with traditional databases.
  • Supports SQL statements.
  • He provides integration with the spring framework.
  • It has good performance. _

  

Two, JDAC

Java operates relational databases through the Java Database Connectivity (JDBC) API, but JDBC is a very low-level API, and we need to write a lot of code to complete the operation of the database.

I'll start with the most traditional JDBC code and then compare the two when MyBatis is introduced.

Step 1: Create a database

   

Step 2: Student entity class

 1 package com.nf;
 2 
 3 import java.sql.Date;
 4 
 5 public class Student {
 6 
 7     private Integer stuid;
 8     private String name;
 9     private String email;
10     private Date dob;
11 
12     public Integer getStuid() {
13         return stuid;
14     }
15 
16     public void setStuid(Integer stuid) {
17         this.stuid = stuid;
18     }
19 
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name;
26     }
27 
28     public String getEmail() {
29         return email;
30     }
31 
32     public void setEmail(String email) {
33         this.email = email;
34     }
35 
36     public Date getDob() {
37         return dob;
38     }
39 
40     public void setDob(Date dob) {
41         this.dob = dob;
42     }
43 
44     @Override
45     public String toString() {
46         return "Student{" +
47                 "stuid=" + stuid +
48                 ", name='" + name + '\'' +
49                 ", email='" + email + '\'' +
50                 ", dob=" + dob +
51                 '}';
52     }
53 }

Step 3: Create the Student Mapper interface

package com.nf;

import java.sql.SQLException;

public interface StudentDao {
    //Method
    public Student findStudentByid(int stuid) ;
}

Step 4: Create the StudentMapperImpl implementation class

package com.nf;

import java.sql.*;

public class StudentDaoImpl implements StudentDao {

    @Override
    public Student findStudentByid(int stuid) throws  SQLException {
        Student student = null;
        Connection connection;

        //Get connection
    String jdbcurl = "jdbc:mysql://localhost:3306/student2?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
    connection =  DriverManager.getConnection(jdbcurl,"root","123456");

        try {
        //Load driver
        Class.forName("com.mysql.cj.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    //Obtain PreparedStatement
    PreparedStatement  pst = connection.prepareStatement("select * from students where stuid=?");
            pst.setInt(1,stuid);
    //Query to get results
    ResultSet rs = pst.executeQuery();
    // Processing result sets
            if(rs.next()){
        student = new Student();
        student.setStuid(rs.getInt("stuid"));
        student.setName(rs.getString("name"));
        student.setEmail(rs.getString("email"));
        student.setDob(rs.getDate("dob"));
    }
            rs.close();
            pst.close();
            connection.close();
        return student;
}

Access to data:

JDBC Disadvantage Analysis:

Each of these methods has a lot of duplicate code: create a connection, create a Statement object, set input parameters, and close resources (such as connection, statement, resultSet).

 

 

 

MyBatis

We're now using MyBatis reality code above:

3.1 Adding Dependencies (pom.xml)

1    <dependency>
2       <groupId>org.mybatis</groupId>
3       <artifactId>mybatis</artifactId>
4       <version>3.5.2</version>
5     </dependency>

 

 

 

3.2 Global Configuration File (config.xml)

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 3         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 4 <!--Root tag-->
 5 <configuration>
 6     <!-- Environments can be configured with multiple,default: Specify which environment to use -->
 7     <environments default="mycom">
 8         <!-- id: Unique identification -->
 9         <environment id="mycom">
10             <!-- Transaction Manager, JDBC Type Transaction Manager -->
11             <transactionManager type="JDBC"/>
12             <!-- Data Source, Pool Type Data Source -->
13             <dataSource type="POOLED">
14                 <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
15                 <property name="url" value="jdbc:mysql://localhost:3306/student2?characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC&amp;rewriteBatchedStatements=true"/>
16                 <property name="username" value="root"/>
17                 <property name="password" value="123456"/>
18             </dataSource>
19         </environment>
20     </environments>
21     <mappers>
22         <mapper resource="StudentMapper.xml"></mapper>
23     </mappers>
24 </configuration>

 

 

 

3.3 Profile StudentMapper.xml (StudentMapper.xml)

Step 1: Configure the SQL statement in the SQL Mapper mapping configuration file, assuming that it is StudentMapper.xml

Query operation:

//StudentMapper.xml
<?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:Root tag, namespace: Namespaces, written casually, are generally guaranteed to be unique -->
<mapper namespace="com.nf.StudentDao" >
<!--
column by java Property name of entity class   property For database attribute names
-->
<resultMap id="myStudent" type="com.nf.Student"> <id column="stuid" property="stuid"></id> <result column="name" property="name"></result> <result column="email" property="email"></result> <result column="dob" property="dob"></result> </resultMap>
<!-- statement,Content: sql Sentence. id: To be the same as the interface method name, be unique under the same namespace resultType: parameter: Types that need to be returned; sql Encapsulation Type of Statement Query Result Set,tb_user That is, the tables in the database --> //query
      
<select id="findStudentByid" parameterType="int" resultMap="myStudent"> SELECT STUID AS stuId, NAME, EMAIL, DOB FROM students WHERE stuid=#{Id} </select>
</mapper>

3.4 Test Class

 1 public class Test2 {
 2     public static void main(String[] args) throws SQLException {
 3         SqlSessionFactory factory = null;
 4         try {
 5             //Files specifying global configuration xml Read the configuration file again
 6            //(This can be compared to a building drawing engineer who wants to build a house. First of all, he has to look at the drawings. Now let's look at the drawings. config.xml Think of it as a drawing.
 7             InputStream inputStream= Resources.getResourceAsStream("config.xml");
 8             // structure sqlSessionFactory(Create a factory)
 9             SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
10             factory = builder.build(inputStream);
11             System.out.println("1.Configured config.xml"+inputStream);
12             System.out.println("2.Create a factory"+factory);
13         } catch (IOException e) {
14             e.printStackTrace();
15         }
16         // Obtain sqlSession(Open factories)
17         SqlSession sqlSession = factory.openSession();
18         System.out.println("3.session"+sqlSession);
19         //StudentMapper Layer (putting things into factory production)                   
20         StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
21         System.out.println("4.Get an instance of the implementation class:"+studentDao);
22         Student student = studentDao.findStudentByid(1);
23         System.out.println(student);
24         
25         sqlSession.close();
26     }
27 }

Delete operation:

Step 1: Write the interface to a method (findStudenrdelete()):

package com.nf;

import java.sql.SQLException;
import java.util.List;

public interface StudentDao {
//    query
    public Student findStudentByid(int stuid) throws SQLException;
//    delete
    public boolean findStudentdelete(int stuid);
    

 

Step 2: Configuration file StudentMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 
 4 
 5 <mapper namespace="com.nf.StudentDao" >
 6 
 7     <resultMap id="myStudent" type="com.nf.Student">
 8         <id column="stuid" property="stuid"></id>
 9         <result column="name" property="name"></result>
10         <result column="email" property="email"></result>
11         <result column="dob" property="dob"></result>
12     </resultMap>
13 
14   //query
15     <select id="findStudentByid"  parameterType="int"  resultMap="myStudent">
16         SELECT STUID AS stuId, NAME, EMAIL, DOB
17          FROM students WHERE stuid=#{Id}
18     </select>
19 
20   //Delete id: Entity class that is consistent with the method name of the interface
21     <delete id="findStudentdelete" parameterType="com.nf.Student">
22           DELETE FROM students WHERE stuid=#{Id}
23     </delete>
24 <mapper>

 

Step 3: Testdelete.java

 

 1 package com.nf;
 2 
 3 import org.apache.ibatis.session.SqlSession;
 4 import org.apache.ibatis.session.SqlSessionFactory;
 5 import org.apache.ibatis.io.Resources;
 6 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 7 
 8 import java.io.IOException;
 9 import java.io.InputStream;
10 
11 
12 //delete
13 public class Test4 {
14     public static void main(String[] args) {
15         SqlSessionFactory factory = null;
16         try {
17             InputStream inputStream = Resources.getResourceAsStream("config.xml");
18             SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
19             factory = builder.build(inputStream);
20         } catch (IOException e) {
21             e.printStackTrace();
22         }
23         SqlSession sqlSession = factory.openSession();
24         StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
25         
26         boolean ok = studentDao.findStudentdelete(1);//Point Interface Method Name
27         if(ok){
28             System.out.println("Delete successful");
29         }else{
30             System.out.println("Delete failed");
31         }
32         sqlSession.commit();
33     }
34 }

 

Add operation:

Step 1: Write the interface to a method (findStudenrdelete()):

package com.nf;

import java.sql.SQLException;
import java.util.List;

public interface StudentDao {
//    query
    public Student findStudentByid(int stuid) throws SQLException;
//    delete
    public boolean findStudentdelete(int stuid);
//    Add to
    public boolean findStudentInsert(Student student);

}

 

Step 2: Step 2: Configuration file StudentMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 
 4 
 5 <mapper namespace="com.nf.StudentDao" >
 6 
 7     <resultMap id="myStudent" type="com.nf.Student">
 8         <id column="stuid" property="stuid"></id>
 9         <result column="name" property="name"></result>
10         <result column="email" property="email"></result>
11         <result column="dob" property="dob"></result>
12     </resultMap>
13 
14 
15     <select id="findStudentByid"  parameterType="int"  resultMap="myStudent">
16         SELECT STUID AS stuId, NAME, EMAIL, DOB
17          FROM students WHERE stuid=#{Id}
18     </select>
19 
20 
21     <delete id="findStudentdelete" parameterType="com.nf.Student">
22         delete  from students where stuid=#{Id}
23     </delete>
24 //Add to
25     <insert id="findStudentInsert parameterType="com.nf.Student"  ">
26         INSERT INTO students(name,email,dob) value(#{name},#{email},#{dob})
27     </insert>
28 <mapper>

Step 3: TestInsert.java

 1 package com.nf;
 2 
 3 import org.apache.ibatis.io.Resources;
 4 import org.apache.ibatis.session.SqlSession;
 5 import org.apache.ibatis.session.SqlSessionFactory;
 6 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 7 
 8 import java.io.IOException;
 9 import java.io.InputStream;
10 import java.sql.Date;
11 import java.sql.SQLException;
12 import java.text.ParseException;
13 import java.text.SimpleDateFormat;
14 
15 //Add to
16 public class Test3 {
17     public static void main(String[] args) throws SQLException {
18         SqlSessionFactory factory = null;
19         try {
20             InputStream inputStream = Resources.getResourceAsStream("config.xml");
21             SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
22             factory = builder.build(inputStream);
23             System.out.println("To configure xml"+inputStream);
24             System.out.println("Create a factory"+factory);
25         } catch (IOException e) {
26             e.printStackTrace();
27         }
28         SqlSession sqlSession = factory.openSession();
29         StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
30         Student student = new Student();
31         //student.setStuid(4);
32         student.setName("Xiaohua");
33         student.setEmail("1084522@qq.com");
34 //        Date conversion
35         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
36         java.util.Date  date = null;
37         try {
38             date= simpleDateFormat.parse("2055-6-2");
39         } catch (ParseException e) {
40             e.printStackTrace();
41         }
42         //new java.sql.Date(date.getTime());
43         student.setDob( new java.sql.Date(date.getTime()));
44         //Not rigorous
45         //student.setDob(Date.valueOf("2055-6-2"));
46         boolean ok =studentDao.findStudentInsert(student);
47         if(ok){
48             System.out.println("Add success");
49         }else{
50             System.out.println("Add failure");
51         }
52         studentDao.findStudentInsert(student);
53 
54         sqlSession.commit();
55         System.out.println(student.getStuid());
56         sqlSession.close();
57     }
58 }

Topics: Java Mybatis xml SQL