Using MyBatis configuration (add, delete, change, search)

--- --- restore content begins

Mybatis introductory presentation

A, MyBatis Introduction

  What is MyBtis?

    MyBatis is a simplified and implements the Java data persistence layer (persistence layer) of the open source framework that abstracts a lot of redundant code JDBC, and provides a simple-to-use API for interacting with the database.

    MyBatis, formerly known as iBATIS, iBATIS created by Clinton Begin in 2002. MyBatis 3 is iBATIS new design, support for annotations and Mapper. 

    MyBatis popular mainly because of its simplicity and ease of use. In Java applications, data persistence layer work involved: Java objects from database queries to generate the required data; the data through SQL Java object persistence to the database.

    By abstracting underlying MyBatis JDBC code, automated SQL result set generated Java objects, Java objects persistent data in the database so that the use of the SQL procedure becomes easy. Such as

  Why MyBtis?

  • The most important thing is to eliminate a lot of JDBC is redundant.
  • Learning cost is very low
  • He can work well together with traditional database.
  • It supports SQL statements.
  • He provides integration with spring framework.
  • It introduces better performance.        

  

Two, JDAC

  Java via Java database (Java DataBase Connectivity, JDBC) API to manipulate relational databases, but JDBC is a very low-level API, we need to write a lot of code to complete the operation on the database.

   I will start with the most traditional JDBC code is written from the comparison again after the introduction of MyBatis will compare both obvious.

   Step 1: Create a database

   

   Step Two: 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 StudentMapper Interface

package com.nf;

import java.sql.SQLException;

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

  Step Four: Create the implementation class StudentMapperImpl

package com.nf;

import java.sql.*;

public class StudentDaoImpl implements StudentDao {

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

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

        try{
         // load the driver 
        the Class.forName ( "com.mysql.cj.jdbc.Driver" ); 
    } the catch (a ClassNotFoundException E) { 
        e.printStackTrace (); 
    } 
    // Get the PreparedStatement 
    the PreparedStatement Connection.prepareStatement PST = ( "SELECT * the WHERE stuid = Students from "? ); 
            pst.setInt ( 1 , stuid);
     // query gets results 
    ResultSet rs = pst.executeQuery ();
     // process result sets 
            IF (rs.next ()) { 
        Student = new 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;
}

   retrieve data:

 JDBC disadvantages analysis:

Each of the above methods have a lot of repetitive code: create a connection to create a Statement object, set input parameters, close the resource (e.g., connection, statement, resultSet).

 

 

 

Three, MyBatis

  We now use the above reality MyBatis Code:

  3.1 add-dependent (pom.xml)

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

 

 

 

  3.2 全局配置文件(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 <!--根标签-->
 5 <configuration>
 6     <!-- 环境,可以配置多个,default:指定采用哪个环境 -->
 7     <environments default="mycom">
 8         <!-- id:唯一标识 -->
 9         <environment id="mycom">
10             <!-- 事务管理器,JDBC类型的事务管理器 -->
11             <transactionManager type="JDBC"/>
12             <!-- 数据源,池类型的数据源 -->
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配置文件 StudentMapper.xml ( StudentMapper.xml  )

  第一步: 在 SQL Mapper 映射配置文件中配置 SQL 语句,假定为 StudentMapper.xml 

  查询操作:

//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:根标签,namespace:命名空间,随便写,一般保证命名空间唯一 -->
<mapper namespace="com.nf.StudentDao" >
<!--
column为java实体类的属性名   property为数据库属性名
-->
<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,内容:sql语句。id:要与接口方法名相同,在同一个命名空间下保持唯一 resultType:parameter:需要返回的类型;sql语句查询结果集的封装类型,tb_user即为数据库中的表 --> //查询
      
<select id="findStudentByid" parameterType="int" resultMap="myStudent"> SELECT STUID AS stuId, NAME, EMAIL, DOB FROM students WHERE stuid=#{Id} </select>
</mapper>

 3.4 测试类

 1 public class Test2 {
 2     public static void main(String[] args) throws SQLException {
 3         SqlSessionFactory factory = null;
 4         try {
 5             //指定全局配置的文件xml再读取配置文件
 6            //(这里可以比喻成一个建筑图 工程师要建房子首先要先看图纸,我们现在把config.xml看做是一张图纸)
 7             InputStream inputStream= Resources.getResourceAsStream("config.xml");
 8             // 构建sqlSessionFactory(创建一个工厂)
 9             SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
10             factory = builder.build(inputStream);
11             System.out.println("1.配置的config.xml"+inputStream);
12             System.out.println("2.创建出一个工厂"+factory);
13         } catch (IOException e) {
14             e.printStackTrace();
15         }
16         // 获取sqlSession(打开工厂)
17         SqlSession sqlSession = factory.openSession();
18         System.out.println("3.session"+sqlSession);
19         //StudentMapper层(将东西放进工厂生产)                   
20         StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
21         System.out.println("4.获得实现类的实例:"+studentDao);
22         Student student = studentDao.findStudentByid(1);
23         System.out.println(student);
24         
25         sqlSession.close();
26     }
27 }

  删除操作:

  第一步:接口写入一个方法(findStudenrdelete()):

package com.nf;

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

public interface StudentDao {
//    查询
    public Student findStudentByid(int stuid) throws SQLException;
//    删除
    public boolean findStudentdelete(int stuid);
    

 

  第二步: 配置文件 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   //删除     id:与接口的方法名要一致             Student的实体类
21     <delete id="findStudentdelete" parameterType="com.nf.Student">
22           DELETE FROM students WHERE stuid=#{Id}
23     </delete>
24 <mapper>

 

   第三步:测试类(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 //删除
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);//点接口方法名
27         if(ok){
28             System.out.println("删除成功");
29         }else{
30             System.out.println("删除失败");
31         }
32         sqlSession.commit();
33     }
34 }

 

  添加操作:

  第一步:接口写入一个方法(findStudenrdelete()):

package com.nf;

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

public interface StudentDao {
//    查询
    public Student findStudentByid(int stuid) throws SQLException;
//    删除
    public boolean findStudentdelete(int stuid);
//    添加
    public boolean findStudentInsert(Student student);

}

 

   第二步:第二步: 配置文件 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 //添加
25     <insert id="findStudentInsert parameterType="com.nf.Student"  ">
26         INSERT INTO students(name,email,dob) value(#{name},#{email},#{dob})
27     </insert>
28 <mapper>

   第三步:测试类(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 //添加
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("配置xml"+inputStream);
24             System.out.println("创建出一个工厂"+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("小华");
33         student.setEmail("[email protected]");
34 //        日期转类型
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         //不严谨
45         //student.setDob(Date.valueOf("2055-6-2"));
46         boolean ok =studentDao.findStudentInsert(student);
47         if(ok){
48             System.out.println("添加成功");
49         }else{
50             System.out.println("添加失败");
51         }
52         studentDao.findStudentInsert(student);
53 
54         sqlSession.commit();
55         System.out.println(student.getStuid());
56         sqlSession.close();
57     }
58 }

 

Guess you like

Origin www.cnblogs.com/xym15079750872/p/11666281.html