This article mainly introduces mybatis and its simple use, which is very simple. The relevant content is not in-depth, nor in-depth study of its principle. The focus is on how to use it. There may be some small problems in some places. Please forgive me a lot. Thank you~
1, About Mybatis
MyBatis is an open-source project of apache, ibatis. In 2010, this project was migrated from apache software foundation to google code, and changed its name to MyBatis. Moved to Github in November 2013.
The term iBATIS comes from the combination of "internet" and "abatis". It is a Java based persistence framework. The persistence layer framework provided by iBATIS includes SQL Maps and Data Access Objects (DAOs)
Mybatis
Mybatis is a persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. With the help of mybatis, the workload of persistence layer can be simplified and the coding efficiency can be improved.
Generally speaking, with the help of Mybatis, the code related to database operation can be simplified. In essence, Mybatis is to realize the collection of some functional codes. The workload reduced when using it is actually completed automatically by Mybatis.
2, Preparations for using Mybatis
(1) New project
Use IDEA to create a new Maven project. (it can be simply understood that Maven is a package management tool, in fact, its function is far more than this. For the use of maven, this article will not introduce it here, but refer to the blog of the online tycoon.)
After the project is established, the pom.xml file will be generated automatically. This is the configuration file of maven, and the configuration of Mybatis is also completed here. Initially as follows
Add dependency in pom.xml file
Import the mybatis jar package, please refer to the official tutorial Mybatis Getting started
To operate on the database, import MySQL connector Java
In addition, import some files related to logs or unit tests as required (these are not required, but are required for mybatis and MySQL connector Java)
The specific import code is shown below. In addition, pay attention to choose the version by yourself. Generally, it is recommended to select the latest one.
<dependencies> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.3</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--log--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <!--unit testing--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
Pay attention to import after adding dependency, as follows
(2) Establish database
Create a test database, which has a user table user, and the user table has two fields id and username.
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES (1, 'xiaoming'); INSERT INTO `user` VALUES (2, 'xiaohong'); SET FOREIGN_KEY_CHECKS = 1;
3, Simple use of Mybatis
On the basis of the above preparations, start to write the code.
(1) Establish entity classes corresponding to database tables
There is a user table in the database, so create a user class,
package com.example.domain; import java.io.Serializable; /** * @className: User * @description: User class */ public class User implements Serializable { //User id private Integer id; //User name private String username; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + '}'; } }
(2) Create the data access object (DAO) interface IUser corresponding to the user entity object
Here we also write a method to query the user according to the user id.
package com.example.dao; import com.example.domain.User; /** * @className: IUserDao * @description: User persistence layer interface */ public interface IUserDao { /** * Query users by user name * @return */ User findByUsername(String username); }
(3) Configure the mapping relationship corresponding to IUserDao
In mybatis, use = = mapper = = to process the database. Generally speaking, write sql statements in mapper and execute them
Create IUserDao.xml file (note that in mybatis, mapper is usually written, that is, UserMapper.xml, which is the same, but DAO class is created in front of it and corresponds to it)
<?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"> <!--Be careful namespace With the corresponding DAO The location of the class (Interface) must not be mistaken--> <mapper namespace="com.example.dao.IUserDao"> <!--Query user by user name--> <select id="findByUsername" resultType="com.example.domain.User"> select * from user where username=#{username} </select> </mapper>
(4) Configure mybatis
Create a new configuration file, config.xml (name is optional), which is mainly used to configure the content of the database. Pay attention to the mysql account and database on this machine.
<?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> <!--Configuration environment--> <environments default="mysql"> <!--To configure mysql Environmental Science--> <environment id="mysql"> <!--Configure transaction type--> <transactionManager type="JDBC"/> <!--Configure data sources (connection pools)--> <dataSource type="POOLED"> <!--Configure basic information for connecting to the database--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!--Configuration map file attention location--> <mappers> <mapper class="com.example.dao.IUserDao"/> </mappers> </configuration>
(5) Create test cases
Create a test class MybatisTest in the test directory to test whether the mybatis case can run successfully.
package com.example; import com.example.dao.IUserDao; import com.example.domain.User; 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; /** * @className: MybatisTest * @description: */ public class MybatisTest { public static void main(String[] args) throws IOException { //Read profile InputStream inputStream= Resources.getResourceAsStream("config.xml"); //Create SqlSessionFactory factory SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder(); SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(inputStream); //Create sqlSession object SqlSession sqlSession=sqlSessionFactory.openSession(); //Using sqlSession to create proxy object of dao interface IUserDao userDao=sqlSession.getMapper(IUserDao.class); //Using the proxy object to execute the method is just a test, so you can determine a user name to query User user=userDao.findByUsername("xiaoming"); //Output test System.out.println(user); //Release resources sqlSession.close(); inputStream.close(); } }
Run the test case, and the result is as follows:
As expected.
In addition, the main directory structure of the whole project is as follows (for reference):
Four, summary
It is very convenient to use mybatis to deal with database operations. Then you need to pay attention to configuring the paths of mybatis and mapper, which must correspond one by one.
In general, mybatis is not used alone, but in spring, which makes development more convenient. But it is also necessary to study mybatis alone, which can lay a foundation for learning spring in the future.
2020.03.05