Java:MyBatis讲解实现增删改查

1、配置文件完成增删改查
1.1、查询用户
select元素属性作用
id方法名,必须与接口中方法名相同
parameterType方法参数的类型,可以省略
resultType方法的返回值类型,如果返回集合,可以直接写对象
#{变量名}先使用?占位,后续将具体值赋值给?
${变量名}字符串拼接。会存在SQL注入问题

根据ID查询用户

  1. 在接口中添加方法

        //2、根据id查询用户信息
        User selectById(int id);
    
  2. 在接口映射文件UserMapper.xml配置SQL语句

        <select id="selectById" resultType="User">
            select * from user where id = #{id};
        </select>
    
  3. 执行方法

        @Test
        public void test02() throws IOException {
            //测试框架搭建情况
            //1、标记mybatis的配置环境
            String resource = "mybatis-config.xml";
            //2、加载配置环境的信息
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //3、根据配置信息,生成SqlSessionFactory对象,相当于连接池
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //4、从连接池获取连接
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //5、获取执行sql语句的对象
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //6、调用方法执行sql语句
            User user = mapper.selectById(1);
    
            sqlSession.close();
    
            System.out.println(user);
        }
    
1.2、删除用户

根据ID删除用户

  1. 在接口中添加方法

        //3、根据id删除用户
        void deleteById(int id);
    
  2. 在接口映射文件UserMapper.xml配置SQL语句

        <delete id="deleteById" >
            delete from user where id = #{id};
        </delete>
    
  3. 执行方法

        @Test
        public void test03() throws IOException {
            //测试框架搭建情况
            //1、标记mybatis的配置环境
            String resource = "mybatis-config.xml";
            //2、加载配置环境的信息
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //3、根据配置信息,生成SqlSessionFactory对象,相当于连接池
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //4、从连接池获取连接
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //5、获取执行sql语句的对象
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //6、调用方法执行sql语句
            mapper.deleteById(3);
    
            //7、提交事务
            sqlSession.commit();
    
            sqlSession.close();
        }
    

    **注意:**需要提交事务

1.3、修改用户内容

修改用户信息

  1. 在接口中添加方法

        void updateUser(User user);
    
  2. 在接口映射文件UserMapper.xml配置SQL语句

        <update id="updateUser">
            update user set username = #{username}, birthday = #{birthday},
                            sex = #{sex}, address = #{address} where id = #{id};
        </update>
    
  3. 执行方法

        @Test
        public void test04() throws IOException {
            //测试框架搭建情况
            //1、标记mybatis的配置环境
            String resource = "mybatis-config.xml";
            //2、加载配置环境的信息
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //3、根据配置信息,生成SqlSessionFactory对象,相当于连接池
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //4、从连接池获取连接
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //5、获取执行sql语句的对象
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //6、创建user对象
            User user = new User(1, "小林", Date.valueOf("2002-1-1"), "男", "北京");
    
            //7、调用执行方法
            mapper.updateUser(user);
    
            //8、提交事务
            sqlSession.commit();
    
            sqlSession.close();
        }
    
1.4、添加用户
属性说明
useGeneratedKeystrue,使用mysql生成的主键,获取数据库返回的主键值
keyProperty实体类中对应的属性

添加用户信息

  1. 在接口中添加方法

        //4、添加数据
        void addUser(User user);
    
  2. 在接口映射文件UserMapper.xml配置SQL语句

        <insert id="addUser" useGeneratedKeys="true" keyProperty="id">
            insert into user values (null,#{username},#{birthday},#{sex},#{address});
        </insert>
    
  3. 执行方法

     @Test
        public void test5() throws IOException {
            //测试框架搭建情况
            //1、标记mybatis的配置环境
            String resource = "mybatis-config.xml";
            //2、加载配置环境的信息
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //3、根据配置信息,生成SqlSessionFactory对象,相当于连接池
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //4、从连接池获取连接
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //5、获取执行sql语句的对象
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //6、创建user对象
            User user = new User(null, "小吴", Date.valueOf("2002-1-1"), "男", "北京");
    
            //7、调用执行方法
            mapper.addUser(user);
               //返回自增的主键提供给后续操作,比如注册后的自动登录场景
            System.out.println(user.getId());
    
            //8、提交事务
            sqlSession.commit();
    
            sqlSession.close();
        }
    
2、多参数查询

多参数查询需要注意的问题

假设我们要名字进行模糊查询,同时确定性别,在UserMapper.xml文件中编写SQL语句

    <select id="selectByUser" resultType="User">
        select * from user where username like #{username} and sex = #{sex};
    </select>

当我们进行测试的时候,会发现报错

Error querying database.  Cause: org.apache.ibatis.binding.BindingException: Parameter 'username' not found. Available parameters are [arg1, arg0, param1, param2]
### Cause: org.apache.ibatis.binding.BindingException: Parameter 'username' not found. Available parameters are [arg1, arg0, param1, param2]

这是因为mybatis在多参数条件的时候,默认只按照两种传参方式

  • arg0,arg1
  • param1,param2,param3

所以需要把xml文件改为

    <select id="selectByUser" resultType="User">
        select * from user where username like #{arg0} and sex = #{arg1};
    </select>

mybatis也为我们提供了一些自定义方案

  1. 散装参数:如果方法中有多个参数,需要使用@Param(“SQL参数占位符名称”)

    在对应接口添加注解

        //5、多参数查询
        List<User> selectByUser(@Param("username") String username, @Param("sex") String sex);
    

    当然,使用这种方法,注解里面的内容要和xml文件一致

        <select id="selectByUser" resultType="User">
            select * from user where username like #{username} and sex = #{sex};
        </select>
    
  2. 对象参数:对象的属性名称要和参数占位符名称一致

    把要作为参数的占位符封装成对象传进去

    接口接收对象

        List<User> selectByUser(User user);
    

    测试方法直接传输对象

            User newUser = new User();
    
            newUser.setUsername("%林%");
            newUser.setSex("男");
            List<User> users = mapper.selectByUser(newUser);
    
            sqlSession.close();
    
            for (User user : users) {
                System.out.println(user);
            }
    
  3. Map集合参数:Map的键要和占位符名称一致

    接口中编写

        List<User> selectByUser(Map<String,Object> map);
    

    测试类中传入

            Map<String, Object> map = new HashMap<>();
            map.put("username","%林%");
            map.put("sex","男");
    
            List<User> users = mapper.selectByUser(map);
    

    一样的这边的键需要与xml文件中的占位符名称相同

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小林学习编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值