前言
上一篇文章中我们讲了什么是持久化以及 Mybatis 的相关简介,今天就来看看如何创建一个 Mybatis 入门实例以及如何利用 Mybatis 进行 CRUD。
数据库准备
- 首先,我们来创建一个数据库,用于后序步骤的使用;
CREATE DATABASE test;
USE test;
- 接着创建一个表,用于存放数据;
CREATE TABLE user (
id int(20) NOT NULL AUTO_INCREMENT,
name varchar(30) DEFAULT NULL,
password varchar(30) DEFAULT NULL,
PRIMARY KEY (id)
);
- 向数据库中插入数据
INSERT INTO user (id, name, password) VALUES (1, '村雨遥', '123456'),(2, '张三', '1234567'),(3, '李四', '12345678');
创建 Maven 工程
- 对于如何创建 Maven 工程,可以参照我之前写的一篇文章:利用 IDEA 搭建一个 Maven 项目
- 接着在项目的
pom.xml
中添加 MyBatis、MySQL、Junit 的依赖;
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
编写 MyBatis 实例
- 编写 MyBatis 核心配置文件,在
main/resources
文件下新建mybatis-config.xml
,配置数据库;
<?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/test?useSSL=false&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="12345"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
- 编写 MyBatis 工具类;
package com.cunyu.utils;
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;
/**
* @author : cunyu
* @version : 1.0
* @className : MyBatisUtils
* @date : 2020/7/14 11:38
* @description : MyBatis 工具类
*/
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();
}
}
/**
* @param
* @return
* @description 获取 SqlSession 连接
* @date 2020/7/14 11:46
* @author cunyu1943
* @version 1.0
*/
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
- 接下来创建实体类;
package com.cun.pojo;
/**
* @author : cunyu
* @version : 1.0
* @className : User
* @date : 2020/7/14 11:55
* @description : User 实体类
*/
public class User {
private int id;
private String name;
private String password;
public User() {
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
- 编写 Mapper 接口;
package com.cunyu.dao;
import com.cunyu.pojo.User;
import java.util.List;
/**
* @InterfaceName : UserDao
* @Author : cunyu
* @Date : 2020/7/14 13:49
* @Version : 1.0
* @Description : User 接口
**/
public interface UserDao {
List<User> getUser();
}
- 添加
UserMapper.xml
配置文件;
<?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">
<!--绑定对应Dao/Mapper接口-->
<mapper namespace="com.cunyu.dao.UserDao">
<select id="getUser" resultType="com.cunyu.pojo.User">
select * from user
</select>
</mapper>
- 编写测试类,在
src/test/java/
目录下保持相同的目录结构,然后添加测试类进行测试;
package com.cunyu.dao;
import com.cunyu.pojo.User;
import com.cunyu.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
/**
* @author : cunyu
* @version : 1.0
* @className : UserDaoTest
* @date : 2020/7/14 13:52
* @description : UserDao 接口测试
*/
public class UserDaoTest {
@Test
public void test(){
// 获取 SqlSession 对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 执行 SQL 语句
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUser();
for (User user:userList
) {
System.out.println(user);
}
// 关闭 SqlSession
sqlSession.close();
}
}
- 运行测试类,可以得出如下结果;
查询操作 select
根据各属性来查询用户
- 在
UserDao
中添加对应方法:
/**
* @param name 用户名
* @return 对应用户名的用户对象
* @description 根据用户名获取用户
* @date 2020/7/14 14:52
* @author cunyu1943
* @version 1.0
*/
User getUserByName(String name);
/**
* @param password 密码
* @return 对应密码的用户对象
* @description 根据用户密码获取用户对象
* @date 2020/7/14 14:57
* @author cunyu1943
* @version 1.0
*/
User getUserByPassword(String password);
- 接着在
UserMapper.xml
中添加Select
语句。其中各属性含义如下:
- id:对应接口中的 方法名;
- resultType:SQL 语句执行的返回值;
- parameterType:参数类型;
<select id="getUserById" resultType="com.cunyu.pojo.User">
select * from user where id=#{id}
</select>
<select id="getUserByName" resultType="com.cunyu.pojo.User">
select * from user where name=#{name}
</select>
<select id="getUserByPassword" resultType="com.cunyu.pojo.User">
select * from user where password=#{password}
</select>
- 在测试类中测试即可;
@Test
public void testGetUserById() {
// 执行 SQL 语句
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user = mapper.getUserById(2);
System.out.println(user);
// 关闭 SqlSession
sqlSession.close();
}
@Test
public void testGetUserByName() {
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user = mapper.getUserByName("村雨遥");
System.out.println(user);
sqlSession.close();
}
@Test
public void testGetUserByPassword(){
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user=mapper.getUserByPassword("123456");
System.out.println(user);
sqlSession.close();
}
插入操作 insert
- 首先在
UserDao
接口中添加对应方法
/**
* @description 添加用户
* @param user 待添加的用户对象
* @return
* @date 2020/7/14 15:50
* @author cunyu1943
* @version 1.0
*/
int addUser(User user);
- 在
UserMapper.xml
中添加Insert
语句;
<insert id="addUser" parameterType="com.cunyu.pojo.User">
insert into user(id, name, password) values (#{id},#{name},#{password})
</insert>
- 测试方法中测试;
@Test
public void testAddUser() {
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user = new User(5, "小雨", "6543210");
int i = mapper.addUser(user);
System.out.println(i);
// 提交事务到数据库
sqlSession.commit();
System.out.println("添加用户成功");
sqlSession.close();
}
修改操作 update
- 在
UserDao
添加对应接口;
/**
* @description 根据 id 修改用户
* @param user 待修改的用户对象
* @return
* @date 2020/7/14 16:04
* @author cunyu1943
* @version 1.0
*/
int updateUser(User user);
- 在
UserMapper.xml
中添加update
语句;
<update id="updateUser" parameterType="com.cunyu.pojo.User">
update user set name=#{name},password=#{password} where id=#{id}
</update>
- 测试类中测试;
@Test
public void testUpdateUser(){
// 获取 SqlSession 对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user = mapper.getUserById(1);
user.setPassword("7891011");
int i = mapper.updateUser(user);
sqlSession.commit();
System.out.println("更新数据成功");
sqlSession.close();
}
删除操作 delete
- 在
userDao
中添加接口;
/**
* @description 删除用户
* @param user 待删除的用户
* @return
* @date 2020/7/14 16:21
* @author cunyu1943
* @version 1.0
*/
int deleteUserById(User user);
- 在
UserMapper.xml
中添加delete
语句;
<delete id="deleteUserById" parameterType="com.cunyu.pojo.User">
delete from user where id=#{id}
</delete>
- 在测试类中测试;
@Test
public void testDeleteUser(){
// 获取 SqlSession 对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user = mapper.getUserById(5);
int i = mapper.deleteUserById(user);
sqlSession.commit();
System.out.println("删除数据成功");
sqlSession.close();
}
最后
以上就是我们今天的所有内容了,原创不易,如果你觉得我的文章对你有所帮助,那就帮忙点赞关注吧,我们就下篇文章再见吧 ~