《SSM笔记——Mybatis》3、CRUD

版权声明:本文为博主ExcelMann的原创文章,未经博主允许不得转载。

3、CRUD

作者:ExcelMann,转载需注明。

mapper.xml文件的标签属性:

  • id:对应的Mapper接口的执行方法名;
  • resultType:返回类型
  • parameterType:参数类型

步骤

  1. Mapper接口填写CRUD的方法;
  2. Mapper.xml文件,对应填写CRUD方法的sql;(都是考察sql的简单操作,就不记录了)

注意点

​ 对于增删改,需要提交事务才能持久化到数据库中。

// 增删改需要提交事务
sqlSession.commit();

或者,在工具类中,创建sqlsession实例时,构造参数为true:

public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession(true);
}
3.1、万能的Map传递多个参数到sql

使用Map的好处

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

对于这种add的sql,假设,我们的实体类,或者数据库中的表字段很多,于是就要写出全部的字段,这样会很麻烦。

这个时候就要考虑使用Map!

改为:

<insert id="insertUser" parameterType="map">
    insert into mybatis.user (id,name,pwd) values (#{userId},#{userName},#{userPwd})
</insert>
@Test
public void insertUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    Map<String,Object> map = new HashMap<String,Object>();
    map.put("userId",5);
    map.put("userName","testMapInsert");
    map.put("userPwd",123456);
    
    mapper.insertUser(map);

    // 增删改需要提交事务
    sqlSession.commit();

    sqlSession.close();


}

这样,如果User实体类有更多的字段,不过如果除了这三个需要传参数的字段以外,其他字段都是可以默认为空的话,那么我们就可以利用Map,只传递这三个参数。

同理,也可以用于select等其他需要多个参数的sql的情况中

3.2、思考模糊查询

模糊查询怎么写?

  1. Java代码执行:在java代码部分,传递字符串带有通配符;
List<User> userList = mapper.getUserList("%李%");
  1. xml的sql执行:在sql拼接中使用通配符;
select * from user where name like "%"#{value}"%"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值