当前位置 > it书童 > java > 正文

Mybatis 基于代理 Dao 实现 CRUD 操作

java it书童 2020-08-17 14:04:13 0赞 0踩 257阅读 0评论

数据表初始化

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(32) NOT NULL COMMENT '用户名',
  `birthday` datetime default NULL COMMENT '生日',
  `sex` char(1) default NULL COMMENT '性别',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert  into `user`(`username`,`birthday`,`sex`) values
   ('罗辑','1980-02-27 10:47:08','男'),
   ('章北海','1978-03-16 02:45:01','男'),
   ('程心','1985-10-09 20:29:58','女');

创建 maven 工程

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.13</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

创建 user 实体类

一个标准的 java bean

User 类:与 user 数据表映射

package com.itshutong.domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {
    private int id;
    private String username;
    private Date birthday;
    private String sex;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User{" +
            "id=" + id +
            ", username='" + username + '\'' +
            ", birthday=" + birthday +
            ", sex='" + sex + '\'' +
            '}';
    }
}

创建 QueryVo 类作为查询条件

作为测试自定义封装查询条件的类

package com.itshutong.domain;

public class QueryVo {
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

创建持久层接口

IUserDao 封装持久层接口

package com.itshutong.dao;

import com.itshutong.domain.QueryVo;
import com.itshutong.domain.User;

import java.util.List;

/**
 * 用户的持久层接口
 */
public interface IUserDao {
    /**
     * 查询所有用户
     * @return
     */
    List<User> findAll();

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

    /**
     * 更新用户
     * @param user
     */
    void updateUser(User user);

    /**
     * 根据id删除用户
     * @param id
     */
    void deleteUser(int id);

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    User findById(int id);

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

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

    /**
     * 根据queryVo中的条件查询用户
     * @return
     */
    List<User> findUserByVo(QueryVo vo);
}

创建持久层接口映射文件

IUserDao.xml 将 IUserDao 的方法映射为具体的 sql 语句

<?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">
<mapper namespace="com.itshutong.dao.IUserDao">
    <!--    配置查询结果的列名与实体类的属性名的对应关系,实体类的成员变量名不一定与数据表的字段名相同,加上对应关系更保险-->
    <resultMap id="userMap" type="user">
        <!--        主键字段的对应-->
        <id property="id" column="id"/>
        <!--        非主键字段的对应-->
        <result property="username" column="username"/>
        <result property="birthday" column="birthday"/>
        <result property="sex" column="sex"/>
    </resultMap>

    <select id="findAll" resultMap="userMap">
        select * from user;
    </select>

    <insert id="saveUser" parameterType="user">
        <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
            select last_insert_id();
        </selectKey>
        insert into user(username, birthday, sex) values(#{username},#{birthday},#{sex});
    </insert>

    <update id="updateUser" parameterType="user">
        update user set username=#{username}, birthday=#{birthday}, sex=#{sex} where id = #{id}
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>

    <select id="findById" parameterType="int" resultMap="userMap">
        select * from user where id = #{id}
    </select>

    <select id="findByName" parameterType="String" resultMap="userMap">
        select * from user where username like #{name}
    </select>

    <select id="findTotal" resultType="int">
        select count(id) from user;
    </select>

    <select id="findUserByVo" parameterType="com.itshutong.domain.QueryVo" resultMap="userMap">
        select * from user where username like #{user.username}
    </select>

</mapper>

创建主配置文件

SqlMapConfig.xml 配置 mysql 连接信息

<?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>
    <properties resource="jdbcConfig.properties" />
    <typeAliases>
        <package name="com.itshutong.domain"/>
    </typeAliases>
    <environments default="mysql">
        <environment id="mysql">
            <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="com.itshutong.dao"/>
    </mappers>
</configuration>

创建 jdbcConfig.properties, 填写具体的 mysql 连接

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=Mac_2020Pwd_Root

测试调用

MybatisTest 测试 crud

package com.itshutong.test;

import com.itshutong.dao.IUserDao;
import com.itshutong.domain.QueryVo;
import com.itshutong.domain.User;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class MybatisTest {
    private InputStream in;
    private SqlSession sqlSession;
    private IUserDao userDao;

    @Before
    public void init() throws Exception {
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        sqlSession = factory.openSession();
        userDao = sqlSession.getMapper(IUserDao.class);
    }

    @After
    public void destroy() throws Exception {
        sqlSession.commit();
        sqlSession.close();
        in.close();
    }

    @Test
    public void testFindAll() {
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void testSave() {
        User user = new User();
        user.setUsername("艾AA");
        user.setBirthday(new Date());
        user.setSex("女");
        System.out.println("保存操作之前:" + user); // 保存之前用户id=0
        userDao.saveUser(user);
        System.out.println("保存操作之后:" + user); // 保存之后用户id=mysql的自增id
    }

    @Test
    public void testUpdate() {
        User user = new User();
        user.setId(4);
        user.setUsername("东方延绪");
        user.setBirthday(new Date());
        user.setSex("女");
        userDao.updateUser(user);
    }

    @Test
    public void testDelete() {
        userDao.deleteUser(4);
    }

    @Test
    public void testFindByName() {
        List<User> users = userDao.findByName("%北%");
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void testFindTotal() {
        int count = userDao.findTotal();
        System.out.println(count);
    }

    @Test
    public void testFindByVo() {
        QueryVo vo = new QueryVo();
        User user = new User();
        user.setUsername("%心%");
        vo.setUser(user);
        List<User> users = userDao.findUserByVo(vo);
        for (User user1 : users) {
            System.out.println(user1);
        }
    }

}

源码

关于我
一个文科出身的程序员,追求做个有趣的人,传播有价值的知识,微信公众号主要分享读书思考心得,不会有代码类文章,非程序员的同学请放心订阅
转载须注明出处:https://www.itshutong.com/articles/617/mybatis-implements-crud-operation-based-on-proxy-dao