What is the MyBatis framework?

MyBatis framework:

MyBatis is an open source project of Apache called iBatis. In 2010, this project was migrated to Google Code by Apache Software Foundation and renamed as MyBatis. Migrated to Github in November 2013.

MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all of the JDBC code and manual setting of parameters and fetching result sets. MyBatis can configure and map native information using simple XML or annotations to map interfaces and Java’s POJOs(Plain Old Java Objects) to records in the database.

Through the learning of this video, you can learn to use MyBatis framework in the shortest time, there is no nonsense in this video, it is all dry stuff, the explanation of this video is not academic research, what is used in the project is covered here, if you want to use MyBatis framework in the project immediately, then you just need to finish learning. You can smoothly use MyBatis development.

Watch online: www.bilibili.com/video/BV185.

Data download: www.bjpowernode.com/javavideo/1…

Main problems solved by MyBatis

Reduce the complexity of using JDBC without having to write repeated creation Connetion, Statement; You don’t have to write code to close the resource.

Use Java objects directly to represent the resulting data. Let developers focus on SQL processing. MyBatis takes care of other distractions.

MyBatis can accomplish:

  1. Register the Driver of the database, for example class.forname (” com.mysql.jdbc.driver “)

  2. Create Connection, Statement, and ResultSet objects that must be used in JDBC

  3. Get the SQL from the XML and execute the SQL statement to convert the ResultSet results into Java objects

List<Student> list = new ArrayLsit<>(); ResultSet rs = state.executeQuery(" select * from student "); while(rs.next){ Student student = new Student(); Student. Elegantly-named setName (rs. Get string (" name ")); Student. SetAge (rs. Get int (" age ")); list.add(student); }Copy the code
  1. Close the resource

ResultSet.close() , Statement.close() , Conenection.close()

An introduction to case

  • MyBatis development preparation
  • Build MyBatis development environment to achieve the first case

Prepare using Mybatis

Download the mybatis github.com/mybatis/myb…

Set up MyBatis development environment

(1) create mysql database and table

Database name SSM; The 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;
Copy the code

(2) Create maven project

Create a Maven project with the following information:

Template:

Project coordinates:

(3) Delete the default App class file

(4) Add Maven coordinates

Add maven coordinates to POM.xml:

(5) Add the Maven plugin

(6) Write the Student entity class

Create the package com.bjPowerNode. domain and create the Student class in the package

(7) Write the Dao interface StudentDao

(8) Compile the Dao interface Mapper mapping file studentDao.xml

Requirements:

  1. Create the studentdao.xml file in the DAO package

  2. The name of the StudentDao. XML file is the same as that of the StudentDao interface.

Create MyBatis master profile

Create the resources directory under project SRC /main and set the resources directory to Resources root

Create the master configuration file: name it mybatis. XML

Note: The name of the master configuration file is custom, and the content is as follows:

Support url in Chinese

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

Create test class MyBatisTest

SRC/test/Java/com/bjpowernode/create MyBatisTest. Java file

(11) Configure the log function

Mybatis. XML file to log configuration, can be executed in the console output SQL statements and parameters

Insert operations

(1) Add methods to the StudentDao interface

int insertStudent(Student student);

(2) StudentDao. XML adds the SQL statement

(3) Add test methods

Object analysis of MyBatis

Object use

SqlSession, SqlSessionFactory, etc

(1) Resources

The Resources class, as the name implies, is used to read resource files. There are many ways to load and parse resource files and return different types of IO stream objects.

(2) SqlSessionFactoryBuilder class

SqlSessionFactory is created using the build() method of the SqlSessionFactoryBuilder object. Since the SqlSessionFactoryBuilder object has completed its historical mission after the factory object has been created, it can be destroyed. So, the SqlSessionFactoryBuilder object is typically created as a local object within a method, and the method ends and the object is destroyed.

(3) SqlSessionFactory interface

The SqlSessionFactory interface object is a heavyweight object and is thread-safe, so an application only needs one of these objects. SqlSession creation requires the openSession() method of the SqlSessionFactory interface.

OpenSession (true) : creates a SqlSession with automatic submission function. OpenSession (false) : creates a SqlSession without automatic submission function, and submits openSession() manually: Same as openSession(false) (4) SqlSession interface

The SqlSession interface object is used to perform persistent operations. A SqlSession corresponds to a database session, which begins with the creation of the SqlSession object and ends with the closing of the SqlSession object.

The SqlSession interface object is thread unsafe, so it needs to be closed by calling its close() method immediately before each database session ends. The session is needed again and created again. SqlSession is created inside the method and closed after use.

Creating a utility class

(1) Create MyBatisUtil

package com.bjpowernode.common;

(2) Use MyBatisUtil class

MyBatis uses the traditional Dao development approach

Use the Dao implementation class to manipulate the database

The Dao development

(1) Create the Dao interface implementation class

public class StudentDaoImpl implements StudentDao

(2) implement the interface select method

Test query operation:

Create the StudentDaoImpl object in MyBatisTest class

(3) Implement insert method in the interface

To test the insert

Analysis of traditional Dao development methods

There was a problem with customizing the Dao interface implementation class in the previous example: In fact, Dao implementation class does not do substantive work, it is only through the RELEVANT API of SqlSession to locate the MAPPING file mapper in the CORRESPONDING ID SQL statement, the real work of DB operation is actually completed by the framework through THE SQL in Mapper.

Therefore, MyBatis framework put aside the implementation class of Dao, directly locate to the corresponding SQL statement in the mapping file Mapper, and operate on DB. This approach to Dao implementation is called Mapper’s dynamic proxy approach.

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