Map和模糊查询
1、Map的使用方法和过程
(这个方法是放弃使用User,这个适合参数特别多的东西)
这个在项目中会使用很多,特别注意这种方法
//Map的使用(万能的Map)
int getUserById2(Map<String , Object> map);
<!--Map增加用户的方法,这个是在dao层的xml文件
下面中的#{userid}是根据给Map传的名称来写的
-->
<insert id="getUserById2" parameterType="Map">
insert into mybatis.user(id, name, pwd) values(#{userid},#{username},#{userpwd})
</insert>
SqlSession sqlSession = MabatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
//注意这个实现的方法,自己都写错了
Map<String , Object> map = new HashMap<String, Object>();
map.put("userid",4);
map.put("username","jinyu");
map.put("userpwd","123");
mapper.getUserById2(map);
sqlSession.commit();
sqlSession.close();
2、模糊查询怎么写
//模糊查询的使用方法
List<User> getUserLike(String value);
<!--模糊查询的使用方法-->
<select id="getUserLike" resultType="com.kuang.pojo.User">
select * from mybatis.user where name like #{value}
</select>
<!-- select * from mybatis.user where name like "%"#{value}"%"这种方式可以节约一些东西
这个可能会造成sql注入
-->
SqlSession sqlSession = MabatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userLike = mapper.getUserLike("李%");
for(User user : userLike)
System.out.println(user);
sqlSession.close();
xml中如果没有写resultType,就会报以下的错
### Cause: org.apache.ibatis.executor.ExecutorException: A query was run and no Result Maps were found for the Mapped Statement 'com.kuang.dao.UserDao.getUserLike'. It's likely that neither a Result Type nor a Result Map was specified.
模糊查询的一些问题:如何使用最安全,一般是Java层使用
小结:
- 所有的增删改操作都需要提交事务!
- 接口所有的普通参数,尽量都写上@Param参数,尤其是多个参数时,必须写上!
- 有时候根据业务的需求,可以考虑使用map传递参数!
- 为了规范操作,在SQL的配置文件中,我们尽量将Parameter参数和resultType都写上!
思考题
模糊查询like语句该怎么写?
第1种:在Java代码中添加sql通配符。
string wildcardname = “%smi%”;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
select * from foo where bar like #{value}
</select>
第2种:在sql语句中拼接通配符,会引起sql注入
string wildcardname = “smi”;
list<name> names = mapper.selectlike(wildcardname);
<select id=”selectlike”>
select * from foo where bar like "%"#{value}"%"
</select>