博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MyBatis之二:简单增删改查
阅读量:5936 次
发布时间:2019-06-19

本文共 5578 字,大约阅读时间需要 18 分钟。

  这一篇在上一篇的基础上简单讲解如何进行增删改查操作。

  一、在mybatis的配置文件conf.xml中注册xml与注解映射

  二、在这个com.mybatis.crud包下面新建userMapper.xml文件与IUserMapper接口

    1、userMapper.xml明细如下

insert into users(id_id,name_n,age_a) values(#{id},#{name},#{age})
delete from users where id_id=#{id}
update users set name_n=#{name},age_a=#{age} where id_id =#{id}

    2、IUserMapper接口定义如下

package com.mybatis.crud;import java.util.List;import java.util.Properties;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Result;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;import org.apache.ibatis.type.JdbcType;public interface IUserMapper {    @Insert("insert into users(id_id,name_n,age_a) values(#{id},#{name},#{age})")    public int add(User user);    @Delete("delete from users where id_id=#{id}")    public int deleteById(int id);    @Update("update users set name_n=#{name},age_a=#{age} where id_id =#{id}")    public int update(User user);    @Select("select * from Users where id_id=#{id}")    @Results({            @Result(property = "id", column = "id_id", jdbcType = JdbcType.INTEGER),            @Result(property = "name", column = "name_n", jdbcType = JdbcType.VARCHAR),            @Result(property= "age", column = "age_a", jdbcType = JdbcType.INTEGER) })    public User getById(int id);    @Select("select * from Users")    @Results({        @Result(property = "id", column = "id_id", jdbcType = JdbcType.INTEGER),        @Result(property = "name", column = "name_n", jdbcType = JdbcType.VARCHAR),        @Result(property= "age", column = "age_a", jdbcType = JdbcType.INTEGER) })    public List
getAll();}

  三、新建一个获取SqlSessionFactory的工具类

package com.mybatis.util;import java.io.InputStream;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.mybatis.demo.test;public class MybatisUtils {        public static SqlSessionFactory getFactory(){        String resource = "conf.xml";         InputStream inputStream = test.class.getClassLoader().getResourceAsStream(resource);        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);        return sessionFactory;    }    }

  四、实际测试代码如下

package com.mybatis.crud;import java.util.List;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.junit.Test;import com.mybatis.util.MybatisUtils;public class TestCrud {    //方法名称上面F11键 即可运行测试方法        @Test    public void testAdd() {        SqlSessionFactory factory = MybatisUtils.getFactory();        SqlSession session = factory.openSession(true);        String statement = "com.mybatis.crud.userMapper.addUser";        User user1 = new User();        user1.setId(199);        user1.setName("wrrrugggcj");        user1.setAge(296);        System.out.println("[xml]新增影响行数:"+session.insert(statement, user1));                User user2 = new User();        user2.setId(198);        user2.setName("wrrrugggcjeee");        user2.setAge(26);        IUserMapper userMapper = session.getMapper(IUserMapper.class);        System.out.println("[注解]新增影响行数:"+userMapper.add( user2));                session.close();    }        @Test    public void testUpdate() {        SqlSessionFactory factory = MybatisUtils.getFactory();        //默认手动提交        SqlSession session = factory.openSession();                String statement = "com.mybatis.crud.userMapper.updateUser";        User user1 = new User();        user1.setId(199);        user1.setName("199");        user1.setAge(89);        System.out.println("[xml]修改影响行数:"+session.update(statement, user1));                User user2 = new User();        user2.setId(198);        user2.setName("198");        user2.setAge(89);        IUserMapper userMapper = session.getMapper(IUserMapper.class);        System.out.println("[注解]修改影响行数:"+userMapper.update(user2));                //提交        session.commit();        session.close();            }        @Test    public void testDelete() {        SqlSessionFactory factory = MybatisUtils.getFactory();        SqlSession session = factory.openSession(true);        String statement = "com.mybatis.crud.userMapper.deleteUser";        System.out.println("[xml]删除影响行数:"+session.delete(statement,199));                 IUserMapper userMapper = session.getMapper(IUserMapper.class);        System.out.println("[注解]删除影响行数:"+userMapper.deleteById(198));                 session.close();    }        @Test    public void testGetAllusers() {        SqlSessionFactory factory = MybatisUtils.getFactory();        SqlSession session = factory.openSession(true);        String statement = "com.mybatis.crud.userMapper.getAllUsers";        List
users = session.selectList(statement); System.out.println("[xml]查询用户列表:"+users); IUserMapper userMapper = session.getMapper(IUserMapper.class); System.out.println("[注解]查询用户列表:"+userMapper.getAll()); session.close(); }}

  

  至此,一个基于mybatis的简单增删改就完成了,不过建议在阅读这篇文章的时候先将入门篇看一遍就可以了。

转载于:https://www.cnblogs.com/wucj/p/5148742.html

你可能感兴趣的文章
【Redis】安装PHP的redis驱动(二)
查看>>
java中string和int互相转化
查看>>
什么是序列化,为什么要序列化
查看>>
Java保留小数点后有效数字
查看>>
CommonHelper
查看>>
excel操作for(lutai)
查看>>
Codeforces Round #162 (Div. 2) C. Escape from Stones
查看>>
2017 Multi-University Training Contest - Team 4 phone call(树+lca+并查集)
查看>>
Struts2文件下载
查看>>
error LNK2019: 无法解析的外部符号 _PhInitializePhLib,该符号在函数 _EnumHandle 中被引用...
查看>>
lodash篇之对象深度比较_.isEqual
查看>>
python之鸭子类型
查看>>
新学期的合作
查看>>
[Cloudera Hadoop] CDH 4.0 Quick Start Guide (动手实践,最新版CDH4.0,企业版Hadoop)
查看>>
计划任务管理 之 计划任务工具 cron 的配置和说明
查看>>
Linux 文件系统剖析
查看>>
站立会议1
查看>>
Objective-C - 组合
查看>>
espcms列表页ajax无限加载
查看>>
try-catch的使用(简单用法 )
查看>>