MyBatis的CRUD

Posted anni-qianqian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis的CRUD相关的知识,希望对你有一定的参考价值。

MyBatis的增删改查,特点是只要定义接口,不用实现方法,sql语句在xml中配置,非常方便

文件结构

技术图片

接口UserDao

import com.jinke.domain.QueryVo;
import com.jinke.domain.User;

import java.util.List;

public interface UserDao 
    List<User> findAll();

    void saveUser(User user);

    void updateUser(User user);

    void deleteUser(Integer userId);

    User findById(Integer userId);

    List<User> findByName(String username);

    int findTotal();

    List<User> findUserByVo(QueryVo vo);

实体类User

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

public class User implements Serializable 
    private Integer id;
    private String username;
    private String address;
    private String sex;
    private Date birthday;

    public Integer getId() 
        return id;
    

    public void setId(Integer id) 
        this.id = id;
    

    public String getUsername() 
        return username;
    

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

    public String getAddress() 
        return address;
    

    public void setAddress(String address) 
        this.address = address;
    

    public String getSex() 
        return sex;
    

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

    public Date getBirthday() 
        return birthday;
    

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

    @Override
    public String toString() 
        return "User" +
                "id=" + id +
                ", username=‘" + username + ‘\\‘‘ +
                ", address=‘" + address + ‘\\‘‘ +
                ", sex=‘" + sex + ‘\\‘‘ +
                ", birthday=" + birthday +
                ‘‘;
    

实体封装

public class QueryVo 
    private User user;

    public User getUser() 
        return user;
    

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

SqlMapConfig.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 2.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--配置环境-->
    <environments default="mysql">
        <!--配置mysql的环境-->
        <environment id="mysql">
            <!--配置事务-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment>
    </environments>
    <!--配置映射文件的位置-->
    <mappers>
        <mapper resource="com/jinke/dao/UserDao.xml"/>
    </mappers>
</configuration>

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.jinke.dao.UserDao">

    <!--解决实体属性和表字段不一致的问题-->
    <resultMap id="userMap" type="com.jinke.domain.User">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="address" column="address"/>
        <result property="sex" column="sex"/>
        <result property="birthday" column="birthday"/>
    </resultMap>

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

  <!--  <select id="findAll" resultType="com.jinke.domain.User">
        select * from user;
    </select>-->

    <insert id="saveUser" parameterType="com.jinke.domain.User">
        /*配置插入操作后,获取插入数据的id*/
        <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
            select last_insert_id();
        </selectKey>
        insert into user(username,address,sex,birthday) values(#username,#address,#sex,#birthday);
    </insert>

    <update id="updateUser" parameterType="com.jinke.domain.User">
        update user set username = #username,address = #address,sex = #sex,birthday = #birthday where id = #id;
    </update>

    <delete id="deleteUser" parameterType="Integer">
        delete from user where id = #uid;
    </delete>

    <select id="findById" parameterType="Integer" resultType="com.jinke.domain.User">
        select * from user where id = #uid;
    </select>

    <select id="findByName" parameterType="String" resultType="com.jinke.domain.User">
        select * from user where username like #name
        /*select * from user where username like ‘%$value%‘*/
    </select>

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

    <!--查询类型封装-->
    <select id="findUserByVo" parameterType="com.jinke.domain.QueryVo" resultType="com.jinke.domain.User">
        select * from user where username like #user.username
    </select>
</mapper>

测试类

import com.jinke.dao.UserDao;
import com.jinke.domain.QueryVo;
import com.jinke.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 UserDao userDao;

    @Before
    public void init() throws Exception 
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        sqlSession = factory.openSession();
        userDao = sqlSession.getMapper(UserDao.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("李四");
        user.setAddress("上海");
        user.setBirthday(new Date());
        user.setSex("男");
        userDao.saveUser(user);
    

    @Test
    public void testUpdate() 
        User user = new User();
        user.setId(2);
        user.setUsername("王五");
        user.setAddress("广州");
        user.setBirthday(new Date());
        user.setSex("男");
        userDao.updateUser(user);
    

    @Test
    public void testDelete() 
        userDao.deleteUser(2);
    

    @Test
    public void testFindOne() 
        User user = userDao.findById(1);
        System.out.println(user);
    

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

    @Test
    public void testFindTotal() 
        int total = userDao.findTotal();
        System.out.println("total" + total);
    

    @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 u : users) 
            System.out.println(u);
        
    

欢迎关注我的微信公众号:安卓圈

技术图片

以上是关于MyBatis的CRUD的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis学习总结-MyBatis快速入门的系列教程

MyBatis源码分析二MyBatis回顾

MyBatis源码分析二MyBatis回顾

MyBatis1:MyBatis入门

MyBatis1:MyBatis入门

MyBatis基础——MyBatis初探——MyBatis快速学习