Article directory
1. Introduction to MyBatis
MyBatis is a persistence layer framework that supports common SQL queries, stored procedures, and advanced mapping. It eliminates almost all manual settings of JDBC codes and parameters and retrieval of result sets, and uses simple XML or annotations for configuration and original mapping. Mapping interfaces and Java POJOs into records in the database enables Java developers to use object-oriented programming ideas to operate the database .
For the disadvantages of JDBC programming, MyBatis provides the following solutions, as follows:
① Configure the data connection pool in SqlMapConfig.xml, and use the connection pool to manage the database link;
② MyBatis configures the SQL statement in the MyBatis mapping file, realizing the separation from the Java code;
③ MyBatis automatically maps the Java object to the SQL statement, The type of input parameter is defined through parameterType in Statement;
④ MyBatis automatically maps the SQL execution result to Java object, and the type of output result is defined through resultType in Statement.
2. MyBatis environment construction
1. MyBatis Download
Official address:https://github.com/mybatis/mybatis-3
(1) After opening, slide down and find Download Latest to download the latest version.
(2) Here you can see three packages, the first one is the shelf package we want, and the last two are the source code under different systems, we download the first shelf package.
2. Configure jdk version
File → Project Structure → Project, select your jdk version in 1, the version in 2 is the same as 1, Apply.
3. Create a Maven project
(1) Since Maven is integrated in IDEA, we don't need to download it, and directly use IDEA's default Maven for project construction.
(2) Open the IDEA development tool, click File → new → Project, select Maven, and click Next.
(3) Give your project a name in the first line, and select the location where the project will be stored in the second line. The name of my project here is MyProject. You can create a folder My on the desktop in advance to store project files. (Of course the location is up to you)
不要忘记点击 finish 完成!
(4) After successful creation as shown in the figure, it looks like this.
4. IDEA connects to the database
① View → Tool Windows → DataBase → click the plus sign on the right side of the screen → DataSource → MySQL
② Fill in the following content
It doesn’t matter if the Name value is random, fill in your MySQL user name and password, and fill in the database name in Database. The database we just named is mybatis. The following URL path does not matter if you fill in Database and it will be automatically generated.
③ Click Driver: MySQL → Go to driver, select your database jar package, the location of this package depends on where you installed MySQL.
④ Click Test Connection below, which is a test. If no error is reported below, it means that the connection is successful. In the last step, click Apply. After the connection is successful, it will be displayed on the right side of IDEA.
5. Project file structure
The picture below is my project directory, all of which have been expanded. You should first create various packages and files according to this structure. It is best to have the same name as mine to avoid mistakes later.
项目需要创建的文件我都展开了,target 里面的不用你管是自动生成的!
6. Introduce related dependencies
Copy and paste the following dependency code into the pom.xml file, don't change anything, just copy it!
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
Paste it at this location. As for why my theme color has been changed to white again, hhhhh because the computer is out of battery, I feel that Jio’s eyes are going to X. Okay, let’s get back to business, listen to me, and go to the next step Create a database standby!
7. Create a database from the command line
Create a database from the command line:
create database mybatis;
8. Database configuration file
The db.properties file is the configuration file of the database connection, and related parameters are configured in this file.
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.username=root
mysql.password=123456bb
mysql.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
Copy all my code first, there are three places that you need to modify yourself, 1 is your MySQL user name, 2 is your MySQL password, 3 is the database name, namely mybatis This is the one we just created database!
9. Core configuration file
The MybatisConfig.xml just created is the core configuration file of Mybatis.
<?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>
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- JDBC 驱动-->
<property name="driver" value="${mysql.driver}"/>
<!-- url数据库的 JDBC URL地址。-->
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--引入映射文件-->
<mapper resource="Mapper/UserMapper.xml"/>
</mappers>
</configuration>
If you follow my steps step by step, you don't need to modify anything, you can copy it completely.
3. Entry test procedure
1. Create a table to prepare data
use mybatis;
//创建表
create table Users(
uid int not null auto_increment primary key,
uname varchar(10) not null,
uage int not null
);
//插入数据
insert into Users(uid,uname,uage) values(null,'张三',20),(null,'李四',18);
2. Create POJO entities
The User class under the pojo package is used to encapsulate the properties of the User object.
package com.tyut.pojo;
public class User {
private int uid;
private String uname;
private int uage;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public int getUage() {
return uage;
}
public void setUage(int uage) {
this.uage = uage;
}
}
The name of each variable is consistent with the one in the database, and if you follow me completely, you can copy it directly!
3. Create a mapping file
The UserMapper.xml file under the Mapper folder is the mapping file.
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tyut.pojo.User">
<select id="findById" parameterType="int" resultType="com.tyut.pojo.User">
select * from users where uid = #{id}
</select>
</mapper>
If the above configuration is complete and followed, you can directly copy and paste the above code into your UserMapper.xml file. If the file name or the table name in the database is different, you can modify it yourself. Note that the path is written correctly .
Every time you create a new entity class, you need to create a mapping file. Since creating a mapping file does not provide a header declaration, copying and pasting is also very troublesome, so here we can create a new mapping file by creating a mapping file template. (Of course it doesn't affect this project, you don't need to create it, it's just for convenience)
Specific steps, File → Settings → Editor → File and Code Templates → plus sign
Copy my code in:
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tyut.pojo.User">
</mapper>
别忘了 Apply,下次需要可直接在选项卡中看到 mapperxml!
4. Modify the core configuration file
Continue to open the MybatisConfig.xml file we have created earlier. Now we give it the configuration file path. As for why there is no configuration just now, it is because this path is where the mapping file is located, so we first write the mapping file and then return to it. MybatisConfig.xml sets the path.
<mappers>
<!--配置xxxMapper.xml文件的位置-->
<mapper resource="Mapper/UserMapper.xml"/>
</mappers>
5. Write test class
The test class is in UserTest under Test.
package com.tyut.Test;
import com.tyut.pojo.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 org.junit.Test;
import java.io.Reader;
import java.io.IOException;
public class UserTest {
@Test
public void userFindByTest() {
String resources = "MybatisConfig.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resources);
}catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlMapper.openSession();
User user = session.selectOne("findById",1);
System.out.println("姓名\t年龄");
System.out.println(user.getUname()+"\t"+user.getUage());
session.close();
}
}
operation result: