Author | A Wen, Editor-in-Chief | Guo Rui
头图 | CSDN Download from Oriental IC
Exhibition | CSDN (ID: CSDNnews)
MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all the JDBC code and the work of setting parameters and obtaining result sets. MyBatis can configure and map primitive types, interfaces, and Java POJOs (Plain Old Java Objects) through simple XML or annotations as records in the database.
In the traditional JDBC implementation, we need to write the query process in the java class, which is very inconvenient for later maintenance, and Mybatis can configure the query statement in the configuration file, only need to maintain the mapping relationship, below we Let's see how Snow uses Mybatis together.
Ready to work
First, you need to prepare the following software:
idea
maven
mysql
Create a database and insert data
First, we create a database of mybatis_db, then create a table t_user, in this table we insert a few pieces of data, as follows:
mysql> create database mybatis_db;
Query OK, 1 row affected (0.01 sec)
mysql> use mybatis_db;
Database changed
mysql> create table t_user(
-> id int(32) primary key auto_increment,
-> username varchar(50),
-> jobs varchar(50),
-> phone varchar(16));
Query OK, 0 rows affected, 1 warning (0.01 sec)
mysql> insert into t_user values(1,"zhangsan","teacher","13142767333");
Query OK, 1 row affected (0.01 sec)
mysql> insert into t_user values(2,"lisi","engineer","13142767334");
Query OK, 1 row affected (0.01 sec)
mysql> insert into t_user values(3,"wangwu","pilot","12342767334");
Query OK, 1 row affected (0.00 sec)
mysql>
Configure pom.xml to download the jar package
We create a maven project and configure pom.xml to download the jar packages of mybatis and mysql-connect-java. The current version of mybatis is 3.5.4.
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
The directory of the entire project is as follows:
Configure mybatis-config
Next, we create a configuration file of mybatis-config.xml in idea's resource (if you don't need to right click on the src\main
directory to create a directory, select resource when creating), the content is as follows, the specific does not need too much explanation The configuration file is mainly used to define JDBC related parameters including the driver used, mysql access address, user name and password, and a map file that defines a mybatis through mappers.
<?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="mysql">
<environment id="mysql">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://192.168.10.128:3306/mybatis_db" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml" />
</mappers>
</configuration>
Create user class
Next, we create the User class and generate get and set and toString methods. In idea, we right-click in the IDE and select Generate and then select Getter and Setter and toString () Select all to quickly generate the corresponding get and set method.
The final result is as follows:
package com.mybatis;
public class User {
private Integer id;
private String username;
private String jobs;
private String phone;
public Integer getId() {
return id;
}
public String getUsername() {
return username;
}
public String getJobs() {
return jobs;
}
public String getPhone() {
return phone;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setJobs(String jobs) {
this.jobs = jobs;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", jobs='" + jobs + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
Create test class
Configure UserMapper.xml
Next, we create a mapping file UserMapper.xml and then need to develop a namespace is UserMapper, and then write a select statement, define the id and parameter types and resultType, resultMap refers to describing how to load objects from the database result set, is the most complex and Powerful elements.
<?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="UserMapper">
<!--根据用户编号获取用户信息 -->
<select id="findUserById" parameterType="Integer" resultType="com.mybatis.User">
select * from t_user where id=#{id}
</select>
</mapper>
Then we create a test class to query users based on id:
package com.mybatis;
import java.io.InputStream;
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.jupiter.api.Test;
/**
* @Auth: xxxx
* @E-mail: xxx
* @title: MybatisTest
* @projectName: mybatis
* @description: TODO 描述信息
* @Date 2020/4/7 9:15 下午
**/
public class MybatisTest {
@Test
public void findUserByIdTest() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("findUserById", 1);
System.out.println(user.toString());
sqlSession.close();
}
}
If we want to make fuzzy queries, then define in UserMapper.xml:
<select id="findUserByName" parameterType="String" resultType="com.mybatisdemo.User">
select * from t_user where username like concat('%','${value}','%')
</select>
The use of like concat ('%', '$ {value}', '%') is to prevent the security risks caused by SQL injection.
Then create a new method in the test class to test:
@Test
public void findUserByNameTest() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> users = sqlSession.selectList("findUserByName","g");
for (User user:users){
System.out.println(user.toString());
}
sqlSession.close();
}
as the picture shows:
Next we add new users under test. First, we define an insert element in UserMapper.xml:
<insert id="addUser" parameterType="com.mybatisdemo.User" >
insert into t_user(username,jobs,phone) value (#{username},#{jobs},#{phone})
</insert>
Then write the test interface:
@Test
public void addUser() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setUsername("beiluo");
user.setJobs("DevOps");
user.setPhone("1314566666");
int rows = sqlSession.insert("addUser",user);
if (rows >0){
System.out.println("Success add "+ rows +"data!");
}else{
System.out.println("add data fail!");
}
sqlSession.commit();
sqlSession.close();
}
As follows:
Next test the update:
<update id="updateUserInfo" parameterType="com.mybatisdemo.User">
update t_user set username=#{username},jobs=#{jobs},phone=#{phone} where id =#{id}
</update>
Then write a test class:
@Test
public void updateUserinfo() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(1);
user.setUsername("jike");
user.setJobs("qa");
user.setPhone("13142764432");
int rows = sqlSession.update("updateUserInfo",user);
if (rows >0){
System.out.println("Success update "+ rows +" data!");
}else{
System.out.println("update data fail!");
}
sqlSession.commit();
sqlSession.close();
}
After execution as follows:
Finally, we test the delete function:
<delete id="deleteUser" parameterType="com.mybatisdemo.User" >
delete from t_user where id=#{id}
</delete>
The test classes are as follows:
@Test
public void deleteUser() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int rows = sqlSession.delete("deleteUser",1);
if (rows >0){
System.out.println("Success delete "+ rows +" data!");
}else{
System.out.println("delete data fail!");
}
sqlSession.commit();
sqlSession.close();
}
The results are as follows:
【END】
More exciting recommendations
Tencent interviewer asked me this binary tree, I just happen to be | The Force Program
Machine learning project template: 6 basic steps of ML project
Summary by senior programmers: I will tell you all 6 ways to analyze the Linux process
Today's Welfare: If you leave a comment in the comment area, you can get a ticket for the live broadcast of the "2020 AI Developer Ten Thousand Conference" worth 299 yuan . Come and move your finger and write what you want to say.
Click to read the original text, wonderful to continue!
Every "watching" you order, I take it seriously