MyBatis-02 (Quick Start for Framework)

Framework quick start

Personal blog : www.xiaobeigua.icu

Content list:

  • Start a MyBatis quickly
  • Basic CURD operation
  • MyBatis internal object analysis
  • Use Dao objects

2.1  Introductory case

MyBatis development preparation

Set up MyBatis development environment and realize the first case

2.1.1 Prepare using Mybatis

Download mybatis

https://github.com/mybatis/mybatis-3/releases

2.1.2 Set up MyBatis development environment

(1) Create mysql database and table

Database name ssm; table name student

CREATE TABLE `student` ( `id` int(11) NOT NULL , `name` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

(2) Create maven project

Create a maven project, the information is as follows:

template:

Engineering coordinates:

(3) Delete the App class file created by default

(4) Add maven coordinates

Add maven coordinates to pom.xml:

<dependencies> <dependency> <groupId>junit</groupId>      <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency>   <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId>    <version>3.5.1</version> </dependency>   <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> </dependencies>

(5) Add maven plugin

<build> <resources> <resource> <directory>src/main/java</directory><!--所在的目录--> <includes><!--包括目录下的.properties,.xml 文件都会扫描到--> <include>**/*.properties</include>    <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins>    </build>

(6) Write Student entity class

Create the package com.xiaobeigua.entity, create the Student class in the package

package com.xiaobeigua.entity; public class Student { //属性名和列名一样     private Integer id; private String name; private String email; private Integer age; // set ,get , toString }

(7) Write the Dao interface StudentDao

Create com.xiaobeigua.dao package, create StudentDao interface

package com.xioabeigua.dao; import com.xiaobeigua.entity.Student; import java.util.List; public interface StudentDao { /*查询所有数据*/ List<Student> selectStudents(); }

(8) Write StudentDao.xml mapping file of Dao interface Mapper

Claim:

  1. Create a file StudentDao.xml in the dao package
  2. The name of the StudentDao.xml file must be the same as the interface StudentDao, with the same case sensitivity.
<?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"> <!--namespace:必须有值,自定义的唯一字符串                推荐使用:dao 接口的全限定名称     --> <mapper namespace="com.xiaobeigua.dao.StudentDao"> <!--<select>: 查询数据, 标签中必须是 select 语句id:  sql 语句的自定义名称,推荐使用 dao 接口中方法名称,                   使用名称表示要执行的 sql 语句resultType: 查询语句的返回结果数据类型,使用全限定类名     --> <select id="selectStudents" resultType="com.xiaobeigua.entity.Student"> <!--要执行的 sql 语句--> select id,name,email,age from student </select> </mapper>   

(9) Create MyBatis main configuration file

Create a resources directory under the project src/main and set the resources directory to resources root

Create the main configuration file: name mybatis.xml

Note: The name of the main configuration file is customized, and the content is as follows:

<? xml version ="1.0" encoding ="UTF-8" ?>

<!DOCTYPE  configuration

PUBLIC    "-//mybatis.org//DTD Config 3.0//EN"

" http://mybatis.org/dtd/mybatis-3-config.dtd " >

< configuration >

<!-- Configure mybatis environment -->

< environments default ="mysql" >

<!--id: The name of the data source -->

< environment id ="mysql" >

<!-- Configure transaction type: use JDBC transaction (use Connection 's commit and rollback) -->

< transactionManager type ="JDBC" />

<!-- Data Source dataSource : Create a database Connection object

type: POOLED uses the connection pool of the database

-->

< dataSource type ="POOLED" >

<!-- Four elements to connect to the database -->

< property name ="driver" value ="com.mysql.jdbc.Driver" />

< property name ="url" value ="jdbc:mysql://localhost:3306/ssm" />

< property name ="username" value ="root" />

< property name ="password" value ="123456" />

</ dataSource >

</ environment >

</ environments >

< mappers >

<!-- Tell mybatis the location of the SQL statement to be executed -->

< mapper resource ="com/bjpowernode/dao/StudentDao.xml" />

</ mappers >

</ configuration >

Support Chinese url

jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8

(10) Create a test class MyBatisTest

src/test/java/com/xiaobeigua/ Create MyBatisTest.java file

 @Test public void testStart() throws IOException {    //1.mybatis 主配置文件     String config = "mybatis-config.xml"; //2.读取配置文件     InputStream in = Resources.getResourceAsStream(config); //3.创建 SqlSessionFactory 对象,目的是获取 SqlSession     SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //4.获取 SqlSession,SqlSession 能执行 sql 语句 SqlSession session = factory.openSession(); //5.执行 SqlSession 的 selectList() List<Student> studentList =      session.selectList("com.bjpowernode.dao.StudentDao.selectStudents"); //6.循环输出查询结果     studentList.forEach( student -> System.out.println(student)); //7.关闭 SqlSession,释放资源 session.close();      }

 

List<Student> studentList = session.selectList("com.bjpowernode.dao.StudentDao.selectStudents"); approximately equivalent jdbc code

Connection conn = Get the connection object

String sql=” select id,name,email,age from student”

PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery();

(11) Configure the log function

The mybatis.xml file is added to the log configuration, and the executed sql statements and parameters can be output in the console

< settings >

< setting name ="logImpl" value ="STDOUT_LOGGING" />

</ settings >


2.2 Basic CURD

Query a selectOne

insert ,update ,delete

2.2.1 insert

(1) Add methods to the StudentDao interface

int insertStudent(Student student);

(2) Add sql statement to StudentDao.xml

<insert id="insertStudent"> insert into student(id,name,email,age) values(#{id},#{name},#{email},#{age}) </insert>

(3) Add test method

 @Test public void testInsert() throws IOException { //1.mybatis 主配置文件     String config = "mybatis-config.xml"; //2.读取配置文件     InputStream in = Resources.getResourceAsStream(config); //3.创建 SqlSessionFactory 对象     SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //4.获取 SqlSession SqlSession session = factory.openSession(); //5.创建保存数据的对象          Student student = new Student(); student.setId(1005); student.setName(" 张 丽 "); student.setEmail("[email protected]"); student.setAge(20); //6.执行插入 insert int rows =  session.insert( "com.bjpowernode.dao.StudentDao.insertStudent",student); //7.提交事务     session.commit(); System.out.println("增加记录的行数:"+rows); //8.关闭 SqlSession session.close();   }

2.2.2 update

(1) Add methods to the StudentDao interface

int updateStudent(Student student);

(2) StudentDao.xml adds sql statement

<update id="updateStudent"> update student set age = #{age} where id=#{id} </update>

(3) Add test method

@Test public void testUpdate() throws IOException { //1.mybatis 主配置文件     String config = "mybatis-config.xml"; //2.读取配置文件      InputStream in = Resources.getResourceAsStream(config);    //3.创建 SqlSessionFactory 对象     SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //4.获取 SqlSession SqlSession session = factory.openSession(); //5.创建保存数据的对象     Student student = new Student(); student.setId(1005);//要修改的 id student.setAge(30); //要修改的年龄值     //6.执行更新 update int rows = session.update( "com.bjpowernode.dao.StudentDao.updateStudent",student); //7.提交事务     session.commit(); System.out.println("修改记录的行数:"+rows); //8.关闭 SqlSession session.close();   }

2.2.3 delete

(1) Add methods to the StudentDao interface

     int deleteStudent(int id);

(2) StudentDao.xml adds sql statement

<delete id="deleteStudent"> delete from student where id=#{studentId} </delete>

(3) Add test method

@Test  public void testDelete() throws IOException { //1.mybatis 主配置文件        String config = "mybatis-config.xml"; //2.读取配置文件     InputStream in = Resources.getResourceAsStream(config); //3.创建 SqlSessionFactory 对象     SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //4.获取 SqlSession SqlSession session = factory.openSession(); //5.删除的 id int id = 1001; //6.执行删除 delete int rows = session.delete( "com.bjpowernode.dao.StudentDao.deleteStudent",id); //7.提交事务     session.commit(); System.out.println("修改记录的行数:"+rows);      //8.关闭 SqlSession session.close();   }

2.3 MyBatis object analysis

2.3.1 Object usage

SqlSession, SqlSessionFactory etc.

(1) Resources class

The Resources class, as the name implies, is a resource, which is used to read resource files. There are many ways to return different types of IO stream objects by loading and parsing resource files.

(2) SqlSessionFactoryBuilder class

The creation of SqlSessionFactory requires the use of the build() method of the SqlSessionFactoryBuilder object. Since the SqlSessionFactoryBuilder object has completed its historical mission after creating the factory object, it can be destroyed. Therefore, the SqlSessionFactoryBuilder object is generally created as a local object within a method, the method ends, and the object is destroyed.

(3) SqlSessionFactory interface

The SqlSessionFactory interface object is a heavyweight object (an object with high system overhead) and is thread-safe, so an application only needs one of this object. To create a SqlSession, you need to use the openSession() method of the SqlSessionFactory interface.

  • openSession(true) : Create a SqlSession with automatic submission function
  • openSession(false) : To create a SqlSession with non-automatic submission function, you need to submit it manually
  • openSession(): same as openSession(false)

(4) SqlSession interface

The SqlSession interface object is used to perform persistence operations. A SqlSession corresponds to a database session. A session starts with the creation of the SqlSession object and ends with the closing of the SqlSession object.

The SqlSession interface object is not thread-safe, so before the end of each database session, you need to call its close() method immediately to close it. The session is needed again, create it again. SqlSession is created inside the method and closed after use.


2.3.2 Create Tool Class

(1) Create the MyBatisUtil class

package. xiaobeigua.common; public class MyBatisUtil { //定义 SqlSessionFactory private static SqlSessionFactory factory = null; static { //使用 静态块 创建一次 SqlSessionFactory try{ String config = "mybatis-config.xml"; //读取配置文件             InputStream in = Resources.getResourceAsStream(config); //创建 SqlSessionFactory 对象             factory = new SqlSessionFactoryBuilder().build(in);  }catch (Exception e){ factory = null; e.printStackTrace(); } } 

/* Get SqlSession object */

public static SqlSession getSqlSession(){ SqlSession session = null; if( factory != null){ session = factory.openSession(); } return session; } }

(2) Use the MyBatisUtil class

@Test public void testUtils() throws IOException {    SqlSession session = MyBatisUtil.getSqlSession(); List<Student> studentList =                session.selectList(    "com.bjpowernode.dao.StudentDao.selectStudents"); studentList.forEach( student -> System.out.println(student)); session.close();   }

2.4 MyBatis uses the traditional Dao development method

Use Dao's implementation class to operate the database

2.4.1 Dao Development

(1) Create Dao interface implementation class

public class StudentDaoImpl implements StudentDao

(2) Implement the select method in the interface

public List<Student> selectStudents() { SqlSession session = MyBatisUtil.getSqlSession(); List<Student> studentList =                session.selectList( "com.bjpowernode.dao.StudentDao.selectStudents"); session.close(); return studentList; } 

Test query operation:

Create StudentDaoImpl object in MyBatisTest class

public class MyBatisTest { StudentDao studentDao = new StudentDaoImpl();    }
@Test public void testSelect() throws IOException { final List<Student> studentList = studentDao.selectStudents(); studentList.forEach( stu -> System.out.println(stu)); }

(3) Implement the insert method in the interface

public int insertStudent(Student student) { SqlSession session = MyBatisUtil.getSqlSession(); int nums = session.insert("com.bjpowernode.dao.StudentDao.insertStudent",student); session.commit(); session.close(); return nums; }

Test insert

@Test public void testInsert() throws IOException { Student student = new Student(); student.setId(1006); student.setName("林浩");  student.setEmail("[email protected]"); student.setAge(26);    int nums = studentDao.insertStudent(student); System.out.println("使用 Dao 添加数据:"+nums); }

(4) Implement the update method in the interface

 public int updateStudent(Student student) { SqlSession session = MyBatisUtil.getSqlSession(); int nums = session.insert( "com.bjpowernode.dao.StudentDao.updateStudent",student); session.commit(); session.close(); return nums; }

Test update

@Test public void testUpdate() throws IOException { Student student = new Student(); student.setId(1006); student.setAge(28);      int nums = studentDao.updateStudent(student); System.out.println("使用 Dao 修改数据:"+nums);   }

(5) Implement the delete method in the interface

public int deleteStudent(int id) { SqlSession session = MyBatisUtil.getSqlSession(); int nums = session.insert( "com.bjpowernode.dao.StudentDao.deleteStudent",1006); session.commit(); session.close(); return nums; }

Test delete

 @Test    public void testDelete() throws IOException { int nums = studentDao.deleteStudent(1006); System.out.println("使用 Dao 修改数据:"+nums); }

2.4.2 Analysis of traditional Dao development methods

In the previous example, I found a problem when customizing the Dao interface implementation class: Dao's implementation class does not actually do any substantive work, it just locates the SQL statement of the corresponding id in the mapping file mapper through the relevant API of SqlSession, which is really correct The work of DB operation is actually done by the framework through SQL in the mapper.

Therefore, the MyBatis framework puts aside Dao's implementation class and directly locates the corresponding SQL statement in the mapping file mapper to operate on the DB. This implementation of Dao is called Mapper's dynamic proxy method.

The Mapper dynamic proxy mode does not require programmers to implement the Dao interface. The interface is implemented by the dynamic proxy automatically generated by MyBatis combined with the mapping file.