如何使用 Mybatis 实现数据库 CURD 操作?
作者 | 阿文,责编 | 郭芮
头图 | CSDN 下载自东方IC
出品 | CSDN(ID:CSDNnews)
准备工作
-
idea -
maven -
mysql
创建数据库并插入数据
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>
配置pom.xml 下载jar包
<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>
配置mybatis-config
src\main
目录点击右键创建一个目录,创建的时候选择resource即可),内容如下,具体不需要过多解释,该配置文件主要是定义JDBC相关的参数包括使用的驱动、mysql 访问地址、用户名和密码以及通过mappers 定义一个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>
<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>
创建user类
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 + '\'' +
'}';
}
}
创建测试类
<?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>
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();
}
}
<select id="findUserByName" parameterType="String" resultType="com.mybatisdemo.User">
select * from t_user where username like concat('%','${value}','%')
</select>
@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();
}
<insert id="addUser" parameterType="com.mybatisdemo.User" >
insert into t_user(username,jobs,phone) value (#{username},#{jobs},#{phone})
</insert>
@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();
}
<update id="updateUserInfo" parameterType="com.mybatisdemo.User">
update t_user set username=#{username},jobs=#{jobs},phone=#{phone} where id =#{id}
</update>
@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();
}
<delete id="deleteUser" parameterType="com.mybatisdemo.User" >
delete from t_user where id=#{id}
</delete>
@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();
}