前言

上一篇文章中我们讲了什么是持久化以及 Mybatis 的相关简介,今天就来看看如何创建一个 Mybatis 入门实例以及如何利用 Mybatis 进行 CRUD。

数据库准备

  1. 首先,我们来创建一个数据库,用于后序步骤的使用;
  1. CREATE DATABASE test;
  2. USE test;
  1. 接着创建一个表,用于存放数据;
  1. CREATE TABLE user (
  2. id int(20) NOT NULL AUTO_INCREMENT,
  3. name varchar(30) DEFAULT NULL,
  4. password varchar(30) DEFAULT NULL,
  5. PRIMARY KEY (id)
  6. );
  1. 向数据库中插入数据
  1. INSERT INTO user (id, name, password) VALUES (1, '村雨遥', '123456'),(2, '张三', '1234567'),(3, '李四', '12345678');

创建 Maven 工程

  1. 对于如何创建 Maven 工程,可以参照我之前写的一篇文章:利用 IDEA 搭建一个 Maven 项目
  2. 接着在项目的 pom.xml 中添加 MyBatis、MySQL、Junit 的依赖;
  1. <dependency>
  2. <groupId>org.mybatis</groupId>
  3. <artifactId>mybatis</artifactId>
  4. <version>3.5.5</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>mysql</groupId>
  8. <artifactId>mysql-connector-java</artifactId>
  9. <version>5.1.49</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>junit</groupId>
  13. <artifactId>junit</artifactId>
  14. <version>4.13</version>
  15. <scope>test</scope>
  16. </dependency>

编写 MyBatis 实例

  1. 编写 MyBatis 核心配置文件,在 main/resources 文件下新建 mybatis-config.xml ,配置数据库;
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <environments default="development">
  7. <environment id="development">
  8. <transactionManager type="JDBC"/>
  9. <dataSource type="POOLED">
  10. <property name="driver" value="com.mysql.jdbc.Driver"/>
  11. <property name="url"
  12. value="jdbc:mysql://localhost:3306/test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"/>
  13. <property name="username" value="root"/>
  14. <property name="password" value="12345"/>
  15. </dataSource>
  16. </environment>
  17. </environments>
  18. <mappers>
  19. <mapper resource="UserMapper.xml"/>
  20. </mappers>
  21. </configuration>
  1. 编写 MyBatis 工具类;
  1. package com.cunyu.utils;
  2. import org.apache.ibatis.io.Resources;
  3. import org.apache.ibatis.session.SqlSession;
  4. import org.apache.ibatis.session.SqlSessionFactory;
  5. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. /**
  9. * @author : cunyu
  10. * @version : 1.0
  11. * @className : MyBatisUtils
  12. * @date : 2020/7/14 11:38
  13. * @description : MyBatis 工具类
  14. */
  15. public class MyBatisUtils {
  16. private static SqlSessionFactory sqlSessionFactory;
  17. static {
  18. try {
  19. String resource = "mybatis-config.xml";
  20. InputStream inputStream = Resources.getResourceAsStream(resource);
  21. sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. /**
  27. * @param
  28. * @return
  29. * @description 获取 SqlSession 连接
  30. * @date 2020/7/14 11:46
  31. * @author cunyu1943
  32. * @version 1.0
  33. */
  34. public static SqlSession getSession() {
  35. return sqlSessionFactory.openSession();
  36. }
  37. }
  1. 接下来创建实体类;
  1. package com.cun.pojo;
  2. /**
  3. * @author : cunyu
  4. * @version : 1.0
  5. * @className : User
  6. * @date : 2020/7/14 11:55
  7. * @description : User 实体类
  8. */
  9. public class User {
  10. private int id;
  11. private String name;
  12. private String password;
  13. public User() {
  14. }
  15. public User(int id, String name, String password) {
  16. this.id = id;
  17. this.name = name;
  18. this.password = password;
  19. }
  20. public int getId() {
  21. return id;
  22. }
  23. public void setId(int id) {
  24. this.id = id;
  25. }
  26. public String getName() {
  27. return name;
  28. }
  29. public void setName(String name) {
  30. this.name = name;
  31. }
  32. public String getPassword() {
  33. return password;
  34. }
  35. public void setPassword(String password) {
  36. this.password = password;
  37. }
  38. @Override
  39. public String toString() {
  40. return "User{" +
  41. "id=" + id +
  42. ", name='" + name + '\'' +
  43. ", password='" + password + '\'' +
  44. '}';
  45. }
  46. }
  1. 编写 Mapper 接口;
  1. package com.cunyu.dao;
  2. import com.cunyu.pojo.User;
  3. import java.util.List;
  4. /**
  5. * @InterfaceName : UserDao
  6. * @Author : cunyu
  7. * @Date : 2020/7/14 13:49
  8. * @Version : 1.0
  9. * @Description : User 接口
  10. **/
  11. public interface UserDao {
  12. List<User> getUser();
  13. }
  1. 添加 UserMapper.xml 配置文件;
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <!--绑定对应Dao/Mapper接口-->
  6. <mapper namespace="com.cunyu.dao.UserDao">
  7. <select id="getUser" resultType="com.cunyu.pojo.User">
  8. select * from user
  9. </select>
  10. </mapper>
  1. 编写测试类,在 src/test/java/ 目录下保持相同的目录结构,然后添加测试类进行测试;
  1. package com.cunyu.dao;
  2. import com.cunyu.pojo.User;
  3. import com.cunyu.utils.MybatisUtils;
  4. import org.apache.ibatis.session.SqlSession;
  5. import org.junit.Test;
  6. import java.util.List;
  7. /**
  8. * @author : cunyu
  9. * @version : 1.0
  10. * @className : UserDaoTest
  11. * @date : 2020/7/14 13:52
  12. * @description : UserDao 接口测试
  13. */
  14. public class UserDaoTest {
  15. @Test
  16. public void test(){
  17. // 获取 SqlSession 对象
  18. SqlSession sqlSession = MybatisUtils.getSqlSession();
  19. // 执行 SQL 语句
  20. UserDao mapper = sqlSession.getMapper(UserDao.class);
  21. List<User> userList = mapper.getUser();
  22. for (User user:userList
  23. ) {
  24. System.out.println(user);
  25. }
  26. // 关闭 SqlSession
  27. sqlSession.close();
  28. }
  29. }
  1. 运行测试类,可以得出如下结果;

MyBatis 快速入门实例 - 图1

查询操作 select

根据各属性来查询用户

  1. UserDao 中添加对应方法:
  1. /**
  2. * @param name 用户名
  3. * @return 对应用户名的用户对象
  4. * @description 根据用户名获取用户
  5. * @date 2020/7/14 14:52
  6. * @author cunyu1943
  7. * @version 1.0
  8. */
  9. User getUserByName(String name);
  10. /**
  11. * @param password 密码
  12. * @return 对应密码的用户对象
  13. * @description 根据用户密码获取用户对象
  14. * @date 2020/7/14 14:57
  15. * @author cunyu1943
  16. * @version 1.0
  17. */
  18. User getUserByPassword(String password);
  1. 接着在 UserMapper.xml 中添加 Select 语句。其中各属性含义如下:
  • id:对应接口中的 方法名
  • resultType:SQL 语句执行的返回值;
  • parameterType:参数类型;
  1. <select id="getUserById" resultType="com.cunyu.pojo.User">
  2. select * from user where id=#{id}
  3. </select>
  4. <select id="getUserByName" resultType="com.cunyu.pojo.User">
  5. select * from user where name=#{name}
  6. </select>
  7. <select id="getUserByPassword" resultType="com.cunyu.pojo.User">
  8. select * from user where password=#{password}
  9. </select>
  1. 在测试类中测试即可;
  1. @Test
  2. public void testGetUserById() {
  3. // 执行 SQL 语句
  4. UserDao mapper = sqlSession.getMapper(UserDao.class);
  5. User user = mapper.getUserById(2);
  6. System.out.println(user);
  7. // 关闭 SqlSession
  8. sqlSession.close();
  9. }
  10. @Test
  11. public void testGetUserByName() {
  12. UserDao mapper = sqlSession.getMapper(UserDao.class);
  13. User user = mapper.getUserByName("村雨遥");
  14. System.out.println(user);
  15. sqlSession.close();
  16. }
  17. @Test
  18. public void testGetUserByPassword(){
  19. UserDao mapper = sqlSession.getMapper(UserDao.class);
  20. User user=mapper.getUserByPassword("123456");
  21. System.out.println(user);
  22. sqlSession.close();
  23. }

插入操作 insert

  1. 首先在 UserDao 接口中添加对应方法
  1. /**
  2. * @description 添加用户
  3. * @param user 待添加的用户对象
  4. * @return
  5. * @date 2020/7/14 15:50
  6. * @author cunyu1943
  7. * @version 1.0
  8. */
  9. int addUser(User user);
  1. UserMapper.xml 中添加 Insert 语句;
  1. <insert id="addUser" parameterType="com.cunyu.pojo.User">
  2. insert into user(id, name, password) values (#{id},#{name},#{password})
  3. </insert>
  1. 测试方法中测试;
  1. @Test
  2. public void testAddUser() {
  3. UserDao mapper = sqlSession.getMapper(UserDao.class);
  4. User user = new User(5, "小雨", "6543210");
  5. int i = mapper.addUser(user);
  6. System.out.println(i);
  7. // 提交事务到数据库
  8. sqlSession.commit();
  9. System.out.println("添加用户成功");
  10. sqlSession.close();
  11. }

MyBatis 快速入门实例 - 图2

修改操作 update

  1. UserDao 添加对应接口;
  1. /**
  2. * @description 根据 id 修改用户
  3. * @param user 待修改的用户对象
  4. * @return
  5. * @date 2020/7/14 16:04
  6. * @author cunyu1943
  7. * @version 1.0
  8. */
  9. int updateUser(User user);
  1. UserMapper.xml 中添加 update 语句;
  1. <update id="updateUser" parameterType="com.cunyu.pojo.User">
  2. update user set name=#{name},password=#{password} where id=#{id}
  3. </update>
  1. 测试类中测试;
  1. @Test
  2. public void testUpdateUser(){
  3. // 获取 SqlSession 对象
  4. SqlSession sqlSession = MybatisUtils.getSqlSession();
  5. UserDao mapper = sqlSession.getMapper(UserDao.class);
  6. User user = mapper.getUserById(1);
  7. user.setPassword("7891011");
  8. int i = mapper.updateUser(user);
  9. sqlSession.commit();
  10. System.out.println("更新数据成功");
  11. sqlSession.close();
  12. }

MyBatis 快速入门实例 - 图3

删除操作 delete

  1. userDao 中添加接口;
  1. /**
  2. * @description 删除用户
  3. * @param user 待删除的用户
  4. * @return
  5. * @date 2020/7/14 16:21
  6. * @author cunyu1943
  7. * @version 1.0
  8. */
  9. int deleteUserById(User user);
  1. UserMapper.xml 中添加 delete 语句;
  1. <delete id="deleteUserById" parameterType="com.cunyu.pojo.User">
  2. delete from user where id=#{id}
  3. </delete>
  1. 在测试类中测试;
  1. @Test
  2. public void testDeleteUser(){
  3. // 获取 SqlSession 对象
  4. SqlSession sqlSession = MybatisUtils.getSqlSession();
  5. UserDao mapper = sqlSession.getMapper(UserDao.class);
  6. User user = mapper.getUserById(5);
  7. int i = mapper.deleteUserById(user);
  8. sqlSession.commit();
  9. System.out.println("删除数据成功");
  10. sqlSession.close();
  11. }

MyBatis 快速入门实例 - 图4

最后

以上就是我们今天的所有内容了,原创不易,如果你觉得我的文章对你有所帮助,那就帮忙点赞关注吧,我们就下篇文章再见吧 ~