• MyBatis总结二:增删改查


    上一篇讲述了MyBatis的快速入门,下面在此基础上进行增删改查的操作:

    首先定义dao层的接口:

    package com.zy.dao;
    
    import com.zy.domain.User;
    
    import java.util.List;
    
    public interface UserDao {
        /**
         * 根据id查询用户信息
         */
        public User getUserById(int id);
    
        /**
         * 查询所有用户信息
         */
        public List<User> getUserList();
    
        /**
         * 添加用户信息
         */
        public void addUser(User user);
    
        /**
         * 修改用户信息
         */
        public void updateUser(User user);
    
        /**
         * 根据id删除用户信息
         */
        public void deleteUser(int id);
    }

    然后编写UserMapper中的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">
    <!--
        定义所有用到的sql语句 和 映射关系
        namespace : 当前这个配置文件的唯一标识, 自定义, 但是不能和其他配置文件namespace重复
    -->
    <mapper namespace="userMapper">
        <!--
            定义一条sql语句, 其实就是一个 statement
                select 代表是查询语句, 与其类似的还有 insert, update, delete等
                id : 这条sql语句的唯一标识,自定义,但是不能和其他sql语句重复
                parameterType:  sql语句需要的参数类型, 需要写 类的全路径
                resultType: sql语句返回的结果类型
        -->
        <select id="getUserById" parameterType="int" resultType="com.zy.domain.User">
            <!--这里写具体的sql语句, #{}是占位符, 编译时会被替换成?, 然后注入真实参数-->
            select * from user where id=#{id}
        </select>
        <!--查询所有用户信息-->
        <select id="getUserList" resultType="com.zy.domain.User">
            select * from user
        </select>
        <!--添加用户信息-->
        <insert id="addUser" parameterType="com.zy.domain.User">
            insert into user (id,name,age) values (null,#{name},#{age})
        </insert>
        <!--修改用户信息-->
        <update id="updateUser" parameterType="com.zy.domain.User">
            update user set name=#{name}, age=#{age} where id=#{id}
        </update>
        <!--删除用户信息-->
        <delete id="deleteUser" parameterType="int">
            delete from user where id=#{id}
        </delete>
    </mapper>

    说一下新增User返回id的写法:

        <!--
            useGeneratedKeys : 是否开启自增主键的回显功能
            keyProperty: 对应javabean的属性名
            keyColumn : 对应数据库的列名
        -->
        <insert id="addUser" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
            insert into users values(null,#{username},#{age})
        </insert>

    最后编写接口实现类:

    package com.zy.dao;
    
    import com.zy.domain.User;
    import org.apache.ibatis.session.SqlSession;
    
    import java.util.List;
    
    public class UserDaoImpl implements UserDao {
    
        private SqlSession sqlSession;
    
        //构造函数内传进来一个sqlsession
        public UserDaoImpl(SqlSession sqlSession) {
            this.sqlSession = sqlSession;
        }
    
        @Override
        public User getUserById(int id) {
            return sqlSession.selectOne("userMapper.getUserById", id);
        }
    
        @Override
        public List<User> getUserList() {
            return sqlSession.selectList("userMapper.getUserList");
        }
    
        @Override
        public void addUser(User user) {
            sqlSession.insert("userMapper.addUser", user);
        }
    
        @Override
        public void updateUser(User user) {
            sqlSession.update("userMapper.updateUser", user);
        }
    
        @Override
        public void deleteUser(int id) {
            sqlSession.delete("userMapper.deleteUser", id);
        }
    }

    生成UserDao接口的单元测试:

    package com.zy.dao;
    
    import com.zy.domain.User;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.io.InputStream;
    import java.util.List;
    
    import static org.junit.Assert.*;
    
    public class UserDaoTest {
        UserDao dao;
    
        @Before
        public void setUp() throws Exception {
            String resource = "mybatis-config.xml";
            InputStream inputStream = UserDaoTest.class.getClassLoader().getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            dao = new UserDaoImpl(sqlSession);
        }
    
        @Test
        public void getUserById() throws Exception {
            User user = dao.getUserById(1);
            System.out.println(user);
        }
    
        @Test
        public void getUserList() throws Exception {
            List<User> list = dao.getUserList();
            for (User user : list) {
                System.out.println(user);
            }
        }
    
        @Test
        public void addUser() throws Exception {
            User user = new User();
            user.setName("张学友");
            user.setAge(18);
            dao.addUser(user);
        }
    
        @Test
        public void updateUser() throws Exception {
            //先查
            User user = dao.getUserById(2);
            //后改
            user.setName("刘德华");
            user.setAge(17);
            dao.updateUser(user);
        }
    
        @Test
        public void deleteUser() throws Exception {
            dao.deleteUser(1);
        }
    
    }

    然后运行单元测试即可。

    附上最终的项目结构图:

  • 相关阅读:
    poj1673EXOCENTER OF A TRIANGLE
    poj1474Video Surveillance(半平面交)
    poj1584A Round Peg in a Ground Hole
    poj1696Space Ant(逆时针螺旋形)
    点分治(树分治)
    LCT(link cut tree) 动态树
    树链剖分
    Codeforces Round #475 (Div. 2)
    openCV学习——一、Mat类
    openCV学习——一、图像读取、显示、输出
  • 原文地址:https://www.cnblogs.com/blazeZzz/p/9285972.html
Copyright © 2020-2023  润新知