Mybatis——基于代理Dao实现CRUD操作和输出结果封装

477 阅读3分钟

声明

这篇博客仍然是基于黑马程序员的课程内容所做的笔记。

1.实现CRUD操作

1.1 Mybatis环境搭建步骤

  • 第一步:创建maven工程
  • 第二步:导入坐标
  • 第三步:编写必要代码(实体类和持久层接口)
  • 第四步:编写SqlMapConfig.xml 全局配置文件
  • 第五步:编写映射配置文件
  • 第六步:编写测试类 大致如图所示:

image.png

这些部分的内容在之前博客中的入门案例有更加易懂的介绍,有必要的可以去瞧一瞧。

这里有一个要求:实体类中的属性名和数据库中的列名严格相等,即:

image.png

这里也许会有人问:这是不合理的,为什么一定要相同,在实际的开发中,这些工作有可能是分开的,会遇到不相同的情况。不相同的时候要怎么解决?这个问题的解决会在后面解决

在搭建完环境之后,大致要进行的操作就只在图中的这上个文件中编写了。

image.png

1.2 增

1.在接口文件中添加方法:

    /**
     * 保存用户
     * @param user
     */
    void saveUser(User user);

2.在映射配置文件中编写sql语句

image.png

3.在测试类中编写代码

    /**
     * 测试保存操作
     */
    @Test
    public void testSave() throws IOException {
        User user = new User();
        user.setUsername("zhouysan");
        user.setAddress("guigang");
        user.setSex("m");
        user.setBirthday(new Date());
        System.out.println(user);
        //5.执行方法
        userDao.saveUser(user);

        System.out.println(user);
    }

注意!!!

看到这里有人会疑惑,为什么没有读取全局配置文件、创建sessionfactory、创建dao代理对象以及释放资源?

因为这一部分代码在每一个方法中都要用到,为了开发效率,故把他们提出来。

image.png

image.png

1.3 删和改

因为删和改比较简单,需要注意的点和上面的增是一样的,所以就放一起直接贴代码了。

1.在接口文件中添加方法:

/**
     * 根据id删除记录
     * @param userId
     */
    void deleteUser(Integer userId);
    
    /**
     * 更新用户
     * @param user
     */
    void updateUser(User user);

2.在映射配置文件中编写sql语句

<!--    删除用户-->
    <delete id="deleteUser" parameterType="Integer">
        delete from user where id=#{id}
    </delete>
    
    <!--    更新用户-->
    <update id="updateUser" parameterType="com.zhouman.domain.User">
        update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}
    </update>

3.在测试类中编写代码

    /**
     * 测试删除操作
     */
    @Test
    public void deleteUser() throws IOException {

        //5.执行方法
        userDao.deleteUser(48);
    }

    /**
     * 测试更新操作
     */
    @Test
    public void updateUser() throws IOException {
        User user = new User();
        user.setId(54);
        user.setUsername("zhouyMO");
        user.setAddress("guigang");
        user.setSex("m");
        user.setBirthday(new Date());

        //5.执行方法
        userDao.updateUser(user);
    }

1.4 查询

1.在接口文件中添加方法:

    /**
     * 根据id查询一个用户信息
     * @param uerId
     * @return
     */
    User findById(Integer uerId);

    /**
     * 根据名称模糊查询用户信息
     * @param username
     * @return
     */
    List<User> findByName(String username);

    /**
     * 查询用户数
     * @return
     */
    int findTotal();

2.在映射配置文件中编写sql语句

<!--    根据id查询用户-->
    <select id="findById" parameterType="INT" resultType="com.zhouman.domain.User">
    select * from user where id=#{id}
    </select>

<!--    根据名称模糊查询用户信息-->
    <select id="findByName" parameterType="String" resultType="com.zhouman.domain.User">
        select * from user where username like #{username}
    </select>

    <!--    获取用户的总记录条数-->
    <select id="findTotal" resultType="int">
        select count(id) from user
    </select>

3.在测试类中编写代码 在模糊查询的方法里有一个细节,那就是要加上%,如若不然就是去xml文件中拼接上%(我认为这种比较麻烦)。

    /**
     * 测试根据id查询操作
     */
    @Test
    public void testFindOne() throws IOException {
        //5.执行方法
        User user = userDao.findById(54);
        System.out.println(user);
    }

    /**
     * 根据名称模糊查询用户信息
     */
    @Test
    public void testfindByName() throws IOException {
        //5.执行方法
        List<User> users = userDao.findByName("%王%");
        for (User user: users) {
            System.out.println(user);
        }
    }

    /**
     * 查询总记录条数
     */
    @Test
    public void testfindTotal() throws IOException {
        //5.执行方法
        int total = userDao.findTotal();
        System.out.println(total);
    }

2. Mybatis的输出结果封装

回答前面博客留下的问题:当实体类的属性名和数据库的表列名不一样时,应该怎么处理?

image.png

2.1 方法一:在xml中写sql语句的时候就给类起别名。

<!-- 配置查询所有操作 -->
    <select id="findAll" resultType="com.itheima.domain.User">
    select id as userId,username as userName,birthday as userBirthday,sex as userSex,address as userAddress from user
    </select>

如图所示,这样就可以对应上了。 image.png 但是这种方法执行效率是高的,但是开发效率不高,需要起别名的sql语句都要写,那还挺麻烦的。所以必须要有另外的方法

2.2 方法二:

1.定义resultMap 在<mapper></mapper>中添加下面标签内容

<resultMap type="com.itheima.domain.User" id="userMap"> 
    <id column="id" property="userId"/>
    <result column="username" property="userName"/>
    <result column="sex" property="userSex"/>
    <result column="address" property="userAddress"/>
    <result column="birthday" property="userBirthday"/>
</resultMap>

image.png

2.调用resultMap的内容

以其中一个方法为例

image.png