通过map操作用户,过程基本相同,但map的key可以不用与user的属性名一致。
假设我们的实体类或者数据库中的表,字段参数过多,我们可以适当的使用map。
1.接口代码
//通过map添加用户
int addUser2(Map<String,Object> map);
2.Mapper.XML代码
<!-- 对象中的属性可以直接取出来,通过map的key传递-->
<insert id="addUser2" parameterType="Map">
insert into user (username,password,phone)values (#{username},#{password},#{phone})
</insert>
3.测试
@Test //通过map增加用户
public void addUser2(){
//增删改需要提交事务
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map <String,Object>map =new HashMap<String,Object>();
map.put("username","溜溜球");
map.put("password","5dsnjkj");
map.put("phone","145265354789");
int i = mapper.addUser2(map);
System.out.println(i>0);
//必须提交事务!!!!!!
sqlSession.commit();
sqlSession.close();
}
模糊查询:
1.接口代码
//模糊查询
List<User> getuserLikelist(String value);
2.Mapper.XML代码
<!-- 模糊查询-->
<select id="getuserLikelist" resultType="com.wei.entity.User">
select * from user where username like #{value}
</select>
3.测试
@Test //模糊查询
public void getuserLikelist(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> getuserlist = mapper.getuserLikelist("%admin%");
for (User user:getuserlist){
System.out.println(user);
}
sqlSession.close();
}