Namespace的包名要和Dao/mapper接口的包名一致!
3.2 select选择,查询语句:
l id :就是对应的namespace 中的方法名;
l resultType :Sql 语句执行的返回值
l parameterType :参数类型
1.编写接口
l //根据id查用户
List<Users> getUserListById(int id);
2.在Mapper.xml中编写sql
<!-- select根据id查询语句-->
<select id="getUserListById" resultType="com.luo.pojo.Users" parameterType="int">
select *from mybatis.user where id=#{id}
</select>
3测试.
@Test3.3 insert
public void test(){
//获取SQLsession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper mapper = sqlSession.getMapper(UsersMapper.class);
List<Users> userListById = mapper.getUserListById(1);
for (Users u:userListById) {
System.out.println(u.toString());
}
sqlSession.close();
}
l id :就是对应的namespace 中的方法名;
l resultType :Sql 语句执行的返回值
l parameterType :参数类型
l //增加用户
int insertUser(Users users);
<!-- insert 增加用户-->
<insert id="insertUser" parameterType="com.luo.pojo.Users" >
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
//增删改需要提交事务3.4 update
@Test
public void insertUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper mapper = sqlSession.getMapper(UsersMapper.class);
int res = mapper.insertUser(new Users(4, "徐慧新", "123456"));
if(res>0){
System.out.println("插入成功");
}
//提交事务
sqlSession.commit();
sqlSession.close();
}
//修改用户
int updateUser(Users users);
<!-- 修改用户-->
<update id="updateUser" parameterType="com.luo.pojo.Users">
update mybatis.user set name =#{name},pwd=#{pwd} where id=#{id}
</update>
@Test
public void updateUsers(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper mapper = sqlSession.getMapper(UsersMapper.class);
int res = mapper.updateUser(new Users(3,"罗军","123456"));
if(res>0){
System.out.println("修改成功");
}
//提交事务
sqlSession.commit();
sqlSession.close();
}
3.5 delete
//删除用户
int deleteUser(int id);
<!-- 删除用户-->
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id}
</delete>
@Test
public void deleteUsers(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper mapper = sqlSession.getMapper(UsersMapper.class);
int res = mapper.deleteUser(2);
if(res>0){
System.out.println("删除成功");
}
sqlSession.commit();
sqlSession.close();
}
增删改需要提交事务
3.6 万能的Map假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应该考虑Map
Map传递参数,直接在sql中取出key即可。 【parameterType=”map”】
对象传递参数,直接在sql中取对象的属性即可 【parameterType=”Object”】
只有一个基本类型参数的情况下,可以直接在Sql中取到。
多个参数用Map,或者注解
//修改
int updataUserByMap(Map<String,Object> map);
<!-- 修改用户-->
<update id="updataUserByMap" parameterType="map">
update mybatis.user set pwd=#{pwd}
where id=#{userId}
</update>
@Test
public void testUpdate(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UsersMapper mapper = sqlSession.getMapper(UsersMapper.class);
HashMap<String, Object>
map = new HashMap<String, Object>();
map.put("userId",1);
map.put("pwd","111111");
int res = mapper.updataUserByMap(map);
if(res>0){
System.out.println("修改成功");
}
sqlSession.commit();
sqlSession.close();
}