MyBatis 教程

MyBatis 入门实例

本章节将通过一个 MyBatis 实例,让你快速 MyBatis 入门。学习 MyBatis 查询、新增、修改和删除操作的基础用法,实现该实例的步骤如下:

  • 配置数据库信息,如:数据库URL、驱动、用户名、密码等信息

  • 编写 mybatis-cfg.xml 配置文件,配置 mybatis 数据源、mapper等

  • 定义数据库 user 表的实体映射类 UserBean

  • 定义 Mapper 接口文件,UserMapper.java 文件

  • 定义 Mapper XML 文件,UserMapper.xml 文件

  • 最后编写测试用例 Main.java 类

实例

实例代码如下:

(1)数据库 database.properties 配置文件

# 数据库信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_test?useUnicode=true&characterEncoding=UTF8
jdbc.username=root
jdbc.password=aaaaaa

(2)mybaits-cfg.xml 配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="database.properties"/>
    <environments default="MySqlDatabase" >
        <environment id="MySqlDatabase" >
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="mybatis.simple.mapper"/>
    </mappers>
</configuration>

(3)定义 user 表的实体类 UserBean.java,代码如下:

package mybatis.simple.mode;
import java.util.Arrays;
import java.util.Date;

public class UserBean {
   private Integer userId;
   private String name;
   private String sex;
   private Integer age;
   private Double salary;
   private Date borthday;
   private byte[] face;
   
   public UserBean() {}
   
   public UserBean(int userId, String name, String sex, int age) {
      this.userId = userId;
      this.name = name;
      this.sex = sex;
      this.age = age;
   }
   
   // 忽略 getter 和 setter 方法
   
   @Override
   public String toString() {
      return "UserBean{" +
            "userId=" + userId +
            ", name='" + name + '\'' +
            ", sex='" + sex + '\'' +
            ", age=" + age +
            ", salary=" + salary +
            ", borthday=" + borthday +
            ", face=" + Arrays.toString(face) +
            '}';
   }
}

(4)定义 Mapper 接口类 UserMapper.java,代码如下:

package mybatis.simple.mapper;
import java.util.List;
import mybatis.simple.mode.UserBean;

public interface UserMapper {
   /** 查询所有用户信息 */
   public List<UserBean> findAll();
   /** 根据ID查询用户信息 */
   public UserBean findById(int userId);
   /** 保存用户信息 */
   public int saveUser(UserBean user);
   /** 更新用户信息 */
   public int updateUser(UserBean user);
   /** 根据用户ID删除用户信息 */
   public int deleteUser(int userId);
}

(5)编写 Mapper XML 文件 UserMapper.xml,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
   "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mybatis.simple.mapper.UserMapper">
   <!-- 映射结果 -->
   <resultMap id="RESULT_MAP" type="mybatis.simple.mode.UserBean">
      <id column="user_id" jdbcType="INTEGER" property="userId" />
      <result column="name" jdbcType="VARCHAR" property="name" />
      <result column="sex" jdbcType="VARCHAR" property="sex" />
      <result column="age" jdbcType="INTEGER" property="age" />
      <result column="salary" jdbcType="DOUBLE" property="salary" />
      <result column="borthday" jdbcType="DATE" property="borthday" />
      <result column="face" jdbcType="LONGVARBINARY" property="face" />
   </resultMap>
   
   <!-- 查询所有用户信息 -->
   <select id="findAll" resultMap="RESULT_MAP">
      select `user_id`, `name`, `sex`, `age`, `salary`, `borthday`, `face`
      from `user`
   </select>
   
   <!-- 根据用户ID查找用户信息 -->
   <select id="findById" parameterType="int" resultMap="RESULT_MAP">
      select `user_id`, `name`, `sex`, `age`, `salary`, `borthday`, `face`
      from `user`
      where `user_id`=#{userId,jdbcType=INTEGER}
   </select>
   
   <!-- 保存用户信息 -->
   <insert id="saveUser">
       INSERT INTO `user`(
           `user_id`, `name`, `sex`, `age`, `salary`, `borthday`, `face`
       ) VALUES (
           #{userId,jdbcType=VARCHAR},
           #{name,jdbcType=VARCHAR},
           #{sex,jdbcType=INTEGER},
           #{age,jdbcType=VARCHAR},
           #{salary,jdbcType=INTEGER},
           #{borthday,jdbcType=VARCHAR},
           #{face,jdbcType=INTEGER}
       )
   </insert>
   
   <!-- 更新用户信息 -->
   <update id="updateUser" parameterType="hashmap">
       UPDATE `user` SET
             `name`=#{name, jdbcType=VARCHAR},
             `sex`=#{sex, jdbcType=VARCHAR},
             `age`=#{age, jdbcType=INTEGER},
             `salary`=#{salary, jdbcType=DOUBLE},
             `borthday`=#{borthday, jdbcType=DATE},
             `face`=#{face, jdbcType=BLOB}
        WHERE `user_id`=#{userId,jdbcType=INTEGER}
   </update>
   
   <!-- 删除用户信息 -->
   <delete id="deleteUser" parameterType="int">
       DELETE FROM `user` WHERE `user_id`=#{userId, jdbcType=INTEGER}
   </delete>
</mapper>

(6)编写测试类 Main.java,代码如下:

package mybatis.simple;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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 mybatis.simple.mapper.UserMapper;
import mybatis.simple.mode.UserBean;
public class Main {

   public static void main(String[] args) throws Exception {
      new Main();
   }
   
   public Main() throws IOException {
      // 获取 Mapper 对象
      String cfgName = "mybatis-cfg.xml";
      InputStream input = Resources.getResourceAsStream(cfgName);
      SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
      SqlSessionFactory sqlFactory = factoryBuilder.build(input);
      SqlSession sqlSession = sqlFactory.openSession(true);
      UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      
      // 插入两个用户
      System.out.println("插入用户信息……");
      UserBean user1 = new UserBean(10, "ZhangSan", "male", 28);
      UserBean user2 = new UserBean(30, "ZhaoLiu", "female", 32);
      userMapper.saveUser(user1);
      userMapper.saveUser(user2);
      
      // 查询所有用户信息
      System.out.println("查询所有用户信息:");
      List<UserBean> userList = userMapper.findAll();
      for(UserBean user : userList) {
         System.out.println("\t用户信息=" + user);
      }
      
      // 查询 ID 等于 10 的用户
      System.out.println("根据ID查询用户信息:");
      UserBean userBean = userMapper.findById(10);
      System.out.println("\t用户信息=" + userBean);
      
      // 更新用户
      System.out.println("更新用户信息:");
      UserBean updateUser = new UserBean(10, "ZhaoLiu-Update", "male", 22);
      userMapper.updateUser(updateUser);
      System.out.println("\t用户信息=" + userMapper.findById(10));
      
      // 删除用户
      System.out.println("删除用户信息……");
      userMapper.deleteUser(10);
      userMapper.deleteUser(30);
   }
}

实例运行结果如下:

插入用户信息……
查询所有用户信息:
    用户信息=UserBean{userId=10, name='ZhangSan', sex='male', age=28, salary=null, borthday=null, face=null}
    用户信息=UserBean{userId=30, name='ZhaoLiu', sex='female', age=32, salary=null, borthday=null, face=null}
根据ID查询用户信息:
    用户信息=UserBean{userId=10, name='ZhangSan', sex='male', age=28, salary=null, borthday=null, face=null}
更新用户信息:
    用户信息=UserBean{userId=10, name='ZhaoLiu-Update', sex='male', age=22, salary=null, borthday=null, face=null}
删除用户信息……

到了这里,你已经对使用 MyBatis 进行开发有一个完整的认识了,在后续的章节将按不同的部分对 MyBatis 进行全面介绍。

说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号