2.Mybatis实现CRUD

2.Mybatis实现CRUD

  • 编写接口
  • 编写mapper对应的sql语句
  • 编写测试语句
1.select

选择、查询语句;

  • id:对应namespace中所定义的方法名
  • resulType:sql语句执行的返回值对应的实体类
  • parameterType:执行方法中所需传入的参数类型
2.insert

插入语句:

<insert id="insertUser" parameterType="com.Z.pojo.User">
    insert into user (id,username,sex,address) values (#{id},#{username},#{sex},#{address})
</insert>

主要操作与查询类似,需要注意增删改需要提交事务。

@Test
public void testInsert() throws ParseException {
    SqlSession sqlSession = MyBatisUtils.getSqlSession();
    IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
    DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date myDate2 = dateFormat2.parse("1998-08-08 08:08:08");
    User user =new User(1,"张三","男","北京市西城区");
    mapper.insertUser(user);
    
    //提交事务
    sqlSession.commit();

    sqlSession.close();
}
3.Update

修改语句:

<update id="updateUser" parameterType="User">
    update user set name=#{username} where id=#{id};
</update>
4.Delete

删除语句:

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

用map作为参数传入,不需要知道数据库对象结构。

假设数据库中的字段涉及参数过多,可以考虑使用map键值对进行传参。、

<insert id="insertUserByMap" parameterType="map">
    insert into user(id,username,sex,address) values (#{iid},#{iUsername},#{iSex},#{iAddress})
</insert>
public void testInsert2() throws ParseException {
    SqlSession sqlSession = MyBatisUtils.getSqlSession();
    IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
    HashMap<String ,Object> map = new HashMap<String, Object>();
    map.put("iid",1);
    map.put("iUsername","张三");
    map.put("iSex","男");
    map.put("iAddress","北京市西城区");

    mapper.insertUserByMap(map);

    //提交事务
    sqlSession.commit();

    sqlSession.close();
}

单个参数时考虑直接传值

多个参数时考虑使用map或者注解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值