使用MyBatis完成CRUD操作

在上一篇文章中,我们了解了为什么要使用MyBatis并完成了入门案例,在这篇文章中,我们具体讲解下如何使用MyBatis完成常用的CRUD操作。

1、查询操作

1.1普通查询

  • SqlMapConfig配置文件
<?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>
    <!--配置mybatis的环境-->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&amp;serverTimezone=UTC"></property>
                <property name="username" value="root"></property>
                <property name="password" value="root"></property>
            </dataSource>
        </environment>
    </environments>
    <!--告知mybatis的映射配置位置-->
    <mappers>
        <mapper resource="com/simon/dao/IUserDao.xml"></mapper>
    </mappers>
</configuration>
  • 配置映射文件IUserDao.xml
<mapper namespace="com.simon.dao.IUserDao">  
<!--查询所有-->
  <select id="findAll" resultType="com.simon.domain.User">
        select * from user
    </select>
    
 <!--查询单个-->
     <select id="findById" resultType="com.simon.domain.User" parameterType="INT">
        <!--当输入参数只有一个时,可以任意名字-->
        select * from user where id= #{id}
    </select>
    
 <!--模糊查询-->
   <select id="findByLike" parameterType="String" resultType="com.simon.domain.User">
        select * from user where username like #{likeNmae}
    </select> 

标签解释

  • namespace:持久层接口的全限定类名
  • select:用于查询的标签
  • id:代理接口中的方法名
  • resultType:用于指定结果集的类型
  • parameterType:用于指定传入参数的类型
  • #{ }:它代表占位符,相当于原来 jdbc 部分所学的?,都是用于执行语句时替换实际的数据,具体的数据是由#{}里面的内容决定的。
  • 测试类编写
public class MyBatisTest {
    private static InputStream in;
    private static SqlSessionFactoryBuilder builder;
    private static SqlSessionFactory factory;
    private static SqlSession session;
    private static IUserDao userDao;

    @Before
    public void init() throws Exception {//测试方法执行前执行
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建sqlSessionFactory的构建者对象
        builder = new SqlSessionFactoryBuilder();
        //使用构建者创建工厂对象sqlSessionFactory
        factory = builder.build(in);
        //4.使用 SqlSessionFactory 生产 SqlSession 对象
        session = factory.openSession();
        //5.使用 SqlSession 创建 dao 接口的代理对象
        userDao = session.getMapper(IUserDao.class);
        //提交事务

    }

    @After
    public void destory() throws Exception {//测试方法执行后执行
        session.commit();
        session.close();
        in.close();
    }

    //测试查询所有方法
    @Test
    public void testFindAll() {
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }
    
       //根据Id查询用户
    @Test
    public void testFiddById(){
        User user=userDao.findById(50);
        System.out.println(user);
    }
    
      //模糊查询User
    @Test
    public void testfindByLike(){
      List<User> users=  userDao.findByLike("%王");
        for (User user:users){
            System.out.println(user);
        }
    }
}

1.2使用聚合函数查询

  • 配置映射文件
 <select id="countUser" resultType="int">
        select count(id) from user
    </select
  • 编写测试类
  @Test
    public void testCountUser(){
        int count=userDao.countUser();
        System.out.println(count);
    }

2、保存操作

  • 配置映射文件
<insert id="inserUser" parameterType="com.simon.domain.User">
        insert into user(username,birthday,sex,address)values (#{username},#{birthday},#{sex},#{address})
    </insert>

标签解释

  • paramterType:代表参数的类型,因为我们要传入的是一个类的对象,所以类型就写类的全名称。

  • #{ }:因为我们提交的属性是一个User对象,所以此处要写User对象的属性名称,它用的是ognl表达式。

ognl表达式:

它是 apache 提供的一种表达式语言,全称是:Object Graphic Navigation Language  对象图导航语,它是按照一定的语法格式来获取数据的。语法格式就是使用  #{对象.对象}的方式。#{user.username}它会先去找 user 对象,然后在 user 对象中找到 username 属性,并调用 getUsername()方法把值取出来。但是我们在 parameterType 属性上指定了实体类名称,所以可以省略 user. 而直接写 username。

  • 测试类的编写
 @Test
    public void testInserUser(){
        User user=new User();
        user.setUsername("Simon");
        user.setSex('男');
        user.setBirthday(new Date());
        user.setAddress("上海松江");
        userDao.inserUser(user);
    }

3、更新操作

  • 配置映射文件
<update id="updateUser" parameterType="com.simon.domain.User">
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id = #{id}
    </update>
  • 编写测试类
 @Test
    public void testUpdateUser(){
        User user=userDao.findById(50);
        user.setAddress("上交大");
        userDao.updateUser(user);
    }

4、删除操作

  • 配置映射文件
<delete id="deleteUser" parameterType="INT">
        delete from user where id=#{uid}
    </delete>
  • 编写测试类
@Test
    public void testDeleteUser(){
        userDao.deleteUser(50);
    }

MyBatis的CRUD_测试类