版权声明:本文为博主ExcelMann的原创文章,未经博主允许不得转载。
3、CRUD
作者:ExcelMann,转载需注明。
mapper.xml文件的标签属性:
- id:对应的Mapper接口的执行方法名;
- resultType:返回类型
- parameterType:参数类型
步骤:
- Mapper接口填写CRUD的方法;
- 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、思考模糊查询
模糊查询怎么写?
- Java代码执行:在java代码部分,传递字符串带有通配符;
List<User> userList = mapper.getUserList("%李%");
- xml的sql执行:在sql拼接中使用通配符;
select * from user where name like "%"#{value}"%"