Mybatis简单的增删改查(CRUD)

Mybatis增删改查

1. 设置mapper.xml

  • namespace:namespace中的包名和mapper接口的包名一致!
  • id:对应的namespace中的方法名
  • resultType:sql语句执行的返回值
  • parameterType:参数类型
<?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">
<!--namespace=绑定一个对应的Mapper接口-->
<mapper namespace="com.zengwen.dao.UserMapper">
    <!--id名为接口的方法名    -->
   <select id="getUserList" resultType="com.zengwen.pojo.User">
       select * from mybatis.user
   </select>
</mapper>

2.select(查询)

2.1编写接口

User getUserById(int id);

2.2编写对应的Mapper

<select id="getUserById" parameterType="int" resultType="com.zengwen.pojo.User">
       select * from mybatis.user where id = #{id}
   </select>

2.3测试

 @Test
    public void getUserId(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper  mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user.toString());
        sqlSession.close();
    }

3.insert(添加)

3.1编写接口

int addUser(User user);

3.2编写对应的Mapper

<insert id="addUser" parameterType="com.zengwen.pojo.User" >
        insert into mybatis.user(id,name, pwd) values (#{id},#{name},#{pwd})
    </insert>

3.3测试

 @Test
    public void addUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper  mapper = sqlSession.getMapper(UserMapper.class);
        mapper.addUser(new User(5,"admin5","123456"));
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

4.update(更新)

4.1编写接口

int updateUser(User user);

4.2编写对应的Mapper

 <update id="updateUser" parameterType="com.zengwen.pojo.User">
        update  mybatis.user set name=#{name},pwd=#{pwd} where id = #{id}
    </update>

4.3测试

@Test
    public void updateUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper  mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUser(new User(5,"admin8","654321"));
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

5.delete(删除)

5.1编写接口

 int deleteUser(int id);

5.2编写对应的Mapper

<delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id = #{id}
    </delete>

5.3测试

 @Test
    public void deleteUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper  mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(5);
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

注意:

  • 增删改的操作一定到提交事务——sqlSession.commit();
  • 增删改查的操作最后一定到关掉sqlSession——Session.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值