zoukankan      html  css  js  c++  java
  • MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作

    该文章是在上篇文章 MyBatis学习总结(一)——MyBatis入门学习 的基础上添加的MyBatis对CRUD的操作

    一、使用MyBatis对表执行CRUD操作——基于XML的实现

    1、定义sql映射xml文件

      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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
          例如namespace="com.myl.mapping.userMapper"就是com.myl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)
     -->
     
    <mapper namespace="com.myl.entity.userMapper">
    
     <!-- 
         在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复
          使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
        resultType="com.myl.entity.User"就表示将查询结果封装成一个User类的对象返回
        User类就是users表所对应的实体类
      -->
     
      <!--根据id查询得到一个user对象-->
     
        <select id="getUser" parameterType="int" resultType="com.myl.entity.User">
            select * from user where id=#{id}
        </select>
        
        <!-- 查找所有数据 -->
        <select id="getAllUser" resultType="com.myl.entity.User">
            select * from user
        </select>
        
        <!-- 添加数据 -->
        <insert id="addUser" parameterType="com.myl.entity.User">
            insert into user (name,age,job,deptno,hdate) values (#{name},#{age},#{job},#{deptno},#{hdate, jdbcType=DATE})
        </insert>
        
        <!-- 修改数据 -->
        <update id="updateUser" parameterType="com.myl.entity.User">
            update user set name=#{name},age=#{age},job=#{job},deptno=#{deptno},hdate=#{hdate} where id=#{id}
        </update>
        
        <!-- 删除数据 -->
        <delete id="deleteUser" parameterType="int">
            delete from user where id=#{id}
        </delete>
    
    </mapper>

    单元测试代码TestCRUD.java

    package com.myl;
    
    import java.util.Date;
    import java.util.List;
    
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import com.myl.entity.User;
    import com.myl.util.MybatisUtil;
    /**
     * 测试 CRUD
     * @author myl
     * @date      2018年4月22日   上午11:23:43
     */
    public class TestCRUD {
    
        @Test
        public void getUserById() {
            SqlSession sqlSession = MybatisUtil.getSession();
            /**
             * 执行操作,getUser 为select的id属性值
             */
            User user = sqlSession.selectOne("getUser", 1);
            System.out.println(user);
            //使用sqlSession执行完sql之后,关闭sqlSession
            sqlSession.close();
        }
        
        @Test
        public void getAllUser(){
            SqlSession sqlSession = MybatisUtil.getSession();
            
            /**
             * 执行查询操作,将查询结果自动封装成List<User>返回
             * getAllUser 为select标签的id属性值
             */
            List<User> userList = sqlSession.selectList("getAllUser");
            
            for(User user : userList){
                System.out.println(user);
            }
            sqlSession.close();
        }
        
        @Test
        public void addUser(){
            SqlSession sqlSession = MybatisUtil.getSession();
            User user = new User();
            user.setName("maoyl");
            user.setAge(15);
            user.setJob("java");
            user.setDeptno(1);
            user.setHdate(new Date());
            /**
             * 执行添加操作
             * addUser为insert的id属性值
             */
            int result = sqlSession.insert("addUser", user);
            /**
             * 手动提交事务
             * 若 SqlSession sqlSession = MybatisUtil.getSession(true); 则不必手动提交事务
             * 若 SqlSession sqlSession = MybatisUtil.getSession(false); 需要手动提交事务
             * 若 SqlSession sqlSession = MybatisUtil.getSession(); 需要手动提交事务
             */
            sqlSession.commit();
            sqlSession.close();
            System.out.println(result);
            
        }
        
        @Test
        public void update(){
            SqlSession sqlSession = MybatisUtil.getSession();
            
            User user = sqlSession.selectOne("getUser", 8);
            if(user == null){
                System.out.println("未查找到数据");
                return;
            }
            user.setName("tangt");
            user.setAge(2);
            user.setJob("techer");
            user.setHdate(new Date());
            int result = sqlSession.update("updateUser", user);
            /**
             * 手动提交事务
             * 若 SqlSession sqlSession = MybatisUtil.getSession(true); 则不必手动提交事务
             * 若 SqlSession sqlSession = MybatisUtil.getSession(false); 需要手动提交事务
             * 若 SqlSession sqlSession = MybatisUtil.getSession(); 需要手动提交事务
             */
            sqlSession.commit();
            sqlSession.close();
            System.out.println(result);
            
        }
        
        @Test
        public void deleteUser(){
            SqlSession sqlSession = MybatisUtil.getSession();
            //若有该数据 result返回 1 删除成功 。若无该数据则result返回 0
            int result = sqlSession.delete("deleteUser", 8);
            /**
             * 手动提交事务
             * 若 SqlSession sqlSession = MybatisUtil.getSession(true); 则不必手动提交事务
             * 若 SqlSession sqlSession = MybatisUtil.getSession(false); 需要手动提交事务
             * 若 SqlSession sqlSession = MybatisUtil.getSession(); 需要手动提交事务
             */
            sqlSession.commit();
            sqlSession.close();
            System.out.println(result);
        }
    
    }

    用到的Mybatis工具类

    package com.myl.util;
    
    import java.io.IOException;
    import java.io.Reader;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    /**
     * @author myl
     * @date      2018年4月22日   上午11:04:57
     * 获取 SqlSessionFactory SqlSession 对象的工具类
     */
    public class MybatisUtil {
        
        /**
         * 获取SqlSessionFactory
         * @return:         SqlSessionFactory   
         * @throws
         */
        public static SqlSessionFactory getSessionFactory(){
            String conf = "mybatisConf.xml";
            Reader reader;
            SqlSessionFactory factory = null;
            try {
                reader = Resources.getResourceAsReader(conf);
                factory = new SqlSessionFactoryBuilder().build(reader);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return factory;
        }
        
        /**
         * 获取 SqlSession
         * @return:         SqlSession   
         * @throws
         */
        public static SqlSession getSession(){
            return getSessionFactory().openSession();
        }
        
        /**
         * 获取 SqlSession 
         * 注:
         *         true 表示创建的SqlSession的对象在执行完sql之后会自动提交事务
         *         false 表示创建的SqlSession的对象在执行完sql之后不会自动提交事务,则需要我们手动提交, 调用sqlSession.commit()即可
         * @param:             @param isAutoCommit
         * @return:         SqlSession   
         * @throws
         */
        public static SqlSession getSession(boolean isAutoCommit){
            return getSessionFactory().openSession(isAutoCommit);
        }
        
    }

    所有测试均通过

    二、使用MyBatis对表执行CRUD操作——基于注解的实现

    1、定义sql映射的接口

      UserMapperInter接口的代码如下:

    package com.myl.mapping;
    
    import java.util.List;
    
    import org.apache.ibatis.annotations.Delete;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Select;
    import org.apache.ibatis.annotations.Update;
    
    import com.myl.entity.User;
    
    public interface UserMapperInter {
        
        @Select("select * from user where id = #{id}")
        public User getUserById(int id);
        
        @Select("select * from user")
        public List<User> getAllUser();
        
        @Insert("insert into user (name,age,job,hdate,deptno) values (#{name},#{age},#{job},#{hdate},#{deptno})")
        public int addUser(User user);
        
        @Update("update user set name = #{name}, age = #{age}, hdate = #{hdate}, deptno = #{deptno} where id = #{id}")
        public int updateUser(User user);
        
        @Delete("delete from user where id = #{id}")
        public int deleteUser(int id);
        
    }

    需要说明的是,我们不需要针对UserMapperI接口去编写具体的实现类代码,这个具体的实现类由MyBatis帮我们动态构建出来,我们只需要直接拿来使用即可。

      2、在conf.xml文件中注册这个映射接口

    <?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>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC" />
                <!-- 配置数据库连接信息 -->
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false"/>
                    <property name="username" value="root"/>
                    <property name="password" value=""/>
                </dataSource>
            </environment>
        </environments>
        
        <mappers>
          <!-- 
            注册userMapper.xml文件, 
             userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml
            -->
            <mapper resource="com/myl/mapping/userMapper.xml"/>
            
            <!-- 注册UserMapper映射接口-->
            <mapper class="com.myl.mapping.UserMapperInter" />
        </mappers>
        
    </configuration>

    单元测试类的代码:

    package com.myl;
    
    
    import java.util.Date;
    import java.util.List;
    
    import org.apache.ibatis.session.SqlSession;
    import org.junit.Test;
    
    import com.myl.entity.User;
    import com.myl.mapping.UserMapperInter;
    import com.myl.util.MybatisUtil;
    
    public class TestCRUD2 {
    
        @Test
        public void getUserById() {
            SqlSession sqlSession = MybatisUtil.getSession();
            UserMapperInter mapper = sqlSession.getMapper(UserMapperInter.class);
            User user = mapper.getUserById(1);
            System.out.println(user);
            sqlSession.close();
        }
        
        @Test
        public void getAllUser(){
            SqlSession sqlSession = MybatisUtil.getSession();
            UserMapperInter mapper = sqlSession.getMapper(UserMapperInter.class);
            List<User> userList = mapper.getAllUser();
            for(User user : userList){
                System.out.println(user);
            }
            sqlSession.close();
        }
        
        @Test
        public void addUser(){
            SqlSession sqlSession = MybatisUtil.getSession();
            UserMapperInter mapper = sqlSession.getMapper(UserMapperInter.class);
            User user = new User();
            user.setName("xqt");
            user.setAge(22);
            user.setJob("java");
            user.setDeptno(4);
            user.setHdate(new Date());
            int result = mapper.addUser(user);
            System.out.println(result);
            sqlSession.commit();
            sqlSession.close();
        }
        
        @Test
        public void updateUser(){
            SqlSession sqlSession = MybatisUtil.getSession();
            UserMapperInter mapper = sqlSession.getMapper(UserMapperInter.class);
            User user = mapper.getUserById(11);
            System.out.println(user);
            if(user == null){
                System.out.println("没有该用户");
                return;
            }
            user.setName("myl");
            user.setAge(2);
            user.setDeptno(3);
            int result = mapper.updateUser(user);
            System.out.println(result);
            sqlSession.commit();
            sqlSession.close();
        }
        
        @Test
        public void deleteUser(){
            SqlSession sqlSession = MybatisUtil.getSession();
            UserMapperInter mapper = sqlSession.getMapper(UserMapperInter.class);
            //如果返回 0 则删除的用户不存在,删除失败
            int result = mapper.deleteUser(12);
            System.out.println(result);
            sqlSession.commit();
            sqlSession.close();
        }
    
    }

    所有测试均通过

    问题:

    引用过mybatisConf.xml引用了 注解的方式,在引用xml配置方式有的方法会报错则会报错。后面详究

  • 相关阅读:
    fetch函数的使用-常见问题
    React的理解-入门指导
    Navicat for mysql 11.1.20激活
    sqlserver使用job删除过期备份文件
    sqlserver删除重复的数据
    提高code效率
    Wampserver红色橙色解决思路----端口冲突是关键
    java mvc框架系列总结ssh,ssm,servlet
    正则表达式入门案例C#
    SpringBoot开发之《兼容http和https同时访问时443端口被占用》
  • 原文地址:https://www.cnblogs.com/maoyali/p/8907350.html
Copyright © 2011-2022 走看看