CRUD
1、namespace
namespace中的包名要和Dao/mapper接口的包名一致!
2、select
选择,查询语句:
id:就是对应的namespace中的方法名;
resultType:sql语句执行的返回值!
parameterType:参数类型!
1、编写接口
//根据ID查询用户
User getUserById(int id);
2、编写对应的mapper中的sql语句
<select id="getUserById" parameterType="int" resultType="com.gx.pojo.User">
select * from mybatis.user where id=#{id}
</select>
3、测试
@Test
public void getUserById(){
SqlSession sqlSession= MybatisUtils.getSqlSession();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
User user= mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
3、Insert
<insert id="addUser" parameterType="com.gx.pojo.User">
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
4、Update
<update id="updateUser" parameterType="com.gx.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
5、Delete
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id};
</delete>
注意点:增删改需要提交事务!
//增删改需要提交事务
@Test
public void addUser(){
SqlSession sqlSession= MybatisUtils.getSqlSession();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
int res=mapper.addUser(new User(5,"发","123123"));
if(res>0){
System.out.println("新增成功");
}
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession= MybatisUtils.getSqlSession();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
int res=mapper.updateUser(new User(5,"你好","123456"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(4);
sqlSession.commit();
sqlSession.close();
}
分析错误
- 标签不要匹配错
- resource绑定mapper,需要使用路径!
- 程序配置文件必须符合规范!
- NullPointerException,没有注册到资源!
- 输出的xml文件中存在中文乱码问题!
- maven资源没有导出问题!
万能Map
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!
//万能map
int addUser2(Map<String, Object> map);
<!-- 对象中的属性,可以直接取出来 传递map的key-->
<insert id="addUser2" parameterType="map" >
insert into mybatis.user (id,name,pwd) values (#{userid},#{username},#{userpwd});
</insert>
@Test
public void addUser2(){
SqlSession sqlSession= MybatisUtils.getSqlSession();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
Map<String,Object> map=new HashMap<String, Object>();
map.put("userid",6);
map.put("userpwd","55555");
mapper.addUser2(map);
sqlSession.close();
}
Map传递参数,直接在sql取出key即可!【parameterType=“map”】
对象传递参数,直接在sql中取对象的属性即可!【parameterType=“Object”】
只有一个基本类型参数的情况下,可以直接在sql中取到!
多个参数用Map,或者注解!
模糊查询
1、Java代码执行的时候,传递通配符%%
List<User> userList = mapper.getUserLike("%李%");
2、在sql拼接中使用通配符!
select * from mybatis.user where name like "%"#{value}"%"