Mybatis增删改查CRUD示例

Java sxdgy 119℃

1.准备工作

创建maven、添加jar包坐标、编写实体类、MyBatis主配置文件、log4j的配置文件等准备工作可以参考:IDEA中Maven工程的MyBatis快速入门

2.编写实体类的持久层映射接口

这里对应的User类持久层映射接口取名UserMapper,放在src/main/java下,代码如下:

package com.gqzzw.mapper;

import com.gqzzw.domain.QueryVo;
import com.gqzzw.domain.User;

import java.util.List;

public interface UserMapper {
    //查询所有用户
    List<User> findAll();
    //查询指定用户
    User findById(int id);
    //使用实体类的包装对象作为查询条件
    List<User> findByVo(QueryVo queryVo);
    //模糊查询
    List<User> findByName(String name);
    //统计用户数量
    int count();
    //保存用户
    void save(User user);
    //修改用户
    void update(User user);
    //删除用户
    void  delete(User user);
}

3.实体类的包装对象

在src/main/java下,编写包装类QueryVo.class,内容如下:

package com.gqzzw.domain;

public class QueryVo {
    private User user;

    public User getUser() {
        return user;
    }

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

4.编写映射接口的配置文件

放在src/main/resources下,必须与久层接口包路径和文件名相同,即:com.gqzzw.mapper.UserMapper.xml

<?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.gqzzw.mapper.UserMapper">
    <!-- 查询所有用户 -->
    <select id="findAll" resultType="com.gqzzw.domain.User">
        select * from user
    </select>
    <!-- 查询指定用户 -->
    <select id="findById" parameterType="int" resultType="com.gqzzw.domain.User">
        select * from user where id=#{uid}
    </select>
    <!-- 使用实体类的包装对象作为查询条件 -->
    <select id="findByVo" parameterType="com.gqzzw.domain.QueryVo" resultType="com.gqzzw.domain.User">
        select * from user where username like #{user.username}
    </select>
    <!-- 模糊查询 -->
    <select id="findByName" parameterType="String" resultType="com.gqzzw.domain.User">
        select * from user where username like #{name}
    </select>
    <!-- 统计用户数量 -->
    <select id="count" resultType="int">
        select count(id) from user
    </select>
    <!-- 保存用户 -->
    <insert id="save" parameterType="com.gqzzw.domain.User">
        <selectKey keyColumn="id" keyProperty="id" resultType="int" order="AFTER">
            select last_insert_id()
        </selectKey>
        insert into user(username,sex) values (#{username},#{sex})
    </insert>
    <!-- 修改用户 -->
    <update id="update" parameterType="com.gqzzw.domain.User">
        update user set username=#{username},sex=#{sex} where id=#{id}
    </update>
    <!-- 删除用户 -->
    <delete id="delete" parameterType="com.gqzzw.domain.User">
        delete from user where id=#{id}
    </delete>
</mapper>

5.编写测试类

放在src/test/java下,编写测试类,内容如下:

package com.gqzzw.mapper;

import com.gqzzw.domain.QueryVo;
import com.gqzzw.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.IOException;
import java.io.InputStream;
import java.util.List;

public class UserMapperTset {
    private InputStream in;
    private SqlSession sqlSession;
    private UserMapper userMapper;

    @Before
    public void init() throws IOException {
        //读取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory的构建者对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //使用构建者创建工厂对象SqlSessionFactory
        SqlSessionFactory factory = builder.build(in);
        //使用SqlSessionFactory产SqlSession对象生
        sqlSession = factory.openSession();
        //产SqlSession对象时可以传true代表自动提交事务
        //sqlSession = factory.openSession(true);
        //使用SqlSession创建映射接口的代理对象
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @After
    public void destroy() throws IOException {
        //提交事务,释放资源
        sqlSession.commit();
        sqlSession.close();
        in.close();
    }
    //查询所有用户
    @Test
    public void findAllTest(){
        //使用代理对象执行查询所有方法
        List<User> users = userMapper.findAll();
        //遍历集合
        for (User user : users) {
            System.out.println(user);
        }
    }
    //查询指定用户
    @Test
    public void  findByIdTest(){
        User user = userMapper.findById(42);
        System.out.println(user);
    }
    //使用实体类的包装对象作为查询条件
    @Test
    public void findByVo(){
        User user = new User();
        user.setUsername("%王%");
        QueryVo queryVo = new QueryVo();
        queryVo.setUser(user);
        List<User> users = userMapper.findByVo(queryVo);
        for (User u : users) {
            System.out.println(u);
        }
    }
    //模糊查询
    @Test
    public void findByName(){
        List<User> users = userMapper.findByName("%王%");
        for (User user : users) {
            System.out.println(user);
        }
    }
    //统计用户数量
    @Test
    public void  countTest(){
        int count = userMapper.count();
        System.out.println(count);
    }
    //保存用户
    @Test
    public void saveTest(){
        User user = new User();
        user.setUsername("05nk.com");
        user.setSex('男');
        userMapper.save(user);
        System.out.println("存储user的id为:"+user.getId());
    }
    //修改用户
    @Test
    public void updateTest(){
        User user = new User(43,"gqzzw",'女');
        userMapper.update(user);
    }
    //删除用户
    @Test
    public void deleteTest(){
        User user = new User();
        user.setId(43);
        userMapper.delete(user);
    }
}

转载请注明:零五博客 » Mybatis增删改查CRUD示例

喜欢 (0)or分享 (0)