Environment description:
- jdk 8 +
- MySQL 8
- maven-3.6.0
- IDEA (Editor)
Require mastery before learning:
- JDBC
- MySQL
- Java Foundation
- Maven
- Junit
Introduction to Mybatis
What is MyBatis
- MyBatis is an excellent persistence framework
- MyBatis avoids almost all JDBC code and the process of manually setting parameters and getting a result set
- MyBatis can use simple XML or annotations to configure and map native information, mapping interfaces and Java entity classes (Plain Old Java Objects, common Java objects) to records in a database.
- MyBatis was originally an open source project for apache, ibatis, which was moved from Apache to google code in 2010 and renamed MyBatis.
- Migrated to Github in November 2013.
- Mybatis official documentation: http://www.mybatis.org/mybatis-3/zh/index.html
- GitHub : https://github.com/mybatis/mybatis-3
Persistence
-
Persistence is the mechanism by which program data is transformed between persistent and transient states.
- That is, to save data, such as objects in memory, to a storage device that can be permanently saved, such as a disk.The main application of persistence is to store in-memory pairs of objects in a database, or in disk files, XML data files, and so on.
- JDBC is a persistence mechanism.File IO is also a persistence mechanism.
- In life: refrigerate fresh meat and defrost it when you eat it.The same is true for canned fruits.
-
Why do I need a persistent service?That's due to a defect in memory itself
- Data is lost when memory is cut off, but there are objects that can't be lost anyway, such as bank accounts. Unfortunately, people can't guarantee that memory never goes out.
- Memory is too expensive. It costs two to three orders of magnitude more than external memory such as hard disks and compact discs. It also costs a lot to maintain. You need to supply power at least all the time.So even if the object doesn't need to be permanently saved, it won't stay in memory because of memory capacity constraints and needs to be persisted to cache to external memory.
Persistence Layer
- What is a persistence layer?
- Code block to complete persistence. --> Dao layer [DAO (Data Access Object) Data Access Object]
- In most cases, especially in enterprise applications, data persistence often means that in-memory data is saved to disk for solidification, while the implementation of persistence is mostly done through a variety of relational databases.
- But here's a word that needs special emphasis, the so-called "layer".For applications, data persistence is an essential component.In other words, our system already has the concept of "persistence layer"?Maybe, but maybe not.Independently of the concept of a "persistence layer" instead of "persistent module" and "persistent unit", this means that there should be a relatively independent logical level in our system architecture, which is dedicated to the implementation of data persistence logic.
- This level should have a clearer and stricter logical boundary than the rest of the system.[To put it plainly, it is used to manipulate the existence of the database!]
Why Mybatis is needed
-
Mybatis is about helping program apes store and retrieve data from databases.
-
Traditional jdbc operations have many repetitive code blocks, such as encapsulation when data is taken out, database connection and so on.Framework can reduce duplicate code and improve development efficiency.
-
MyBatis is a semi-automated ORM framework (Object Relationship Mapping) -->Object Relationship Mapping
All things can still be done without Mybatis, just with it, all the implementation will be simpler!There is no difference between technology and the people who use it. -
Advantages of MyBatis
- Easy to learn: small and simple in itself.There is no third-party dependency, the simplest installation is just two jar files + configure a few sql mapping files, easy to learn, easy to use, through the document and source code, you can have a complete grasp of its design ideas and implementation.
- Flexibility: mybatis does not impose any impact on the existing design of the application or database.sql is written in xml for unified management and optimization.The sql statement can satisfy all the requirements of operating the database.
- Decoupling sql from program code: Separating business logic from data access logic by providing a DAO layer makes the system design clearer, easier to maintain, and easier to unit test.Separation of sql and code improves maintainability.
- Provides xml tags to support writing dynamic sql.
- ...
-
Most importantly, use a lot of people!Company needs!
MyBatis First Program
Idea flow: Set up environment -> Import Mybatis -> Write code -> Test
Code demonstration
- Set up experimental database
CREATE DATABASE `mybatis`; USE `mybatis`; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(20) NOT NULL, `name` varchar(30) DEFAULT NULL, `pwd` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user`(`id`,`name`,`pwd`) values (1,'great','123456'),(2,'Zhang San','abcdef'),(3,'Li Si','987654');
- Import MyBatis related jar packages
- Find on GitHub
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency>
- Write MyBatis Core Profile
- View official documents (to get into the habit of checking your own documents)
<?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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/kuang/dao/userMapper.xml"/> </mappers> </configuration>
- Write MyBatis Tool Class
- View official documents
import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //Get SqlSession Connection public static SqlSession getSession(){ return sqlSessionFactory.openSession(); } }
- Create Entity Class
public class User { private int id; //id private String name; //Full name private String pwd; //Password //Construction, parametric, no parametric //set/get //toString() }
- Writing Mapper interface classes
import com.zheng.pojo.User; import java.util.List; public interface UserMapper { List<User> selectUser(); }
- Write Mapper.xml configuration file
- namespace is important and cannot be written incorrectly!, which corresponds to the interface class you implement
<?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="com.kuang.dao.UserMapper"> <select id="selectUser" resultType="com.kuang.pojo.User"> select * from user </select> </mapper>
- Writing test classes
- Junit Package Test
public class MyTest { @Test public void selectUser() { SqlSession session = MybatisUtils.getSession(); //Method 1: //List<User> users = session.selectList("com.zheng.mapper.UserMapper.selectUser"); //Method 2: UserMapper mapper = session.getMapper(UserMapper.class); List<User> users = mapper.selectUser(); for (User user: users){ System.out.println(user); } session.close(); } }
- Run tests
Problem Description
Possible problem description: Maven static resource filtering problem
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources>
If you do not import your compiled.xml file or.java file and it cannot be imported, errors will be hard to find!