MyBatis-增删改查
三、增删改查实现
- namespace中的包名要和Dao/Mapper接口的包名一致!
- id:就是对应的namespace中的方法
- resultType:sql语句的返回值
- parameterType:传入的参数类型
1、查询
List<User> getUserById(int id);
<select id="getUserById" parameterType="int" resultType="com.lengzher.pojo.User">
select * from mybatis.user where id = #{id};
</select>
@Test
public void getUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
2、增加
int addUser(User user);
<insert id="addUser" parameterType="com.lengzher.pojo.User">
insert into mybatis.user (name, pwd)values(#{name},#{pwd});
</insert>
@Test
public void addUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int rs = mapper.addUser(new User(4, "李二蛋", "123123"));
if(rs>0){
System.out.println("插入成功!");
}
sqlSession.commit();
sqlSession.close();
}
3、修改
int updateUser(User user);
<update id="updateUser" parameterType="com.lengzher.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(4,"李散单","123"));
sqlSession.commit();
sqlSession.close();
}
4、删除
int delUser(int id);
<delete id="delUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>
@Test
public void delUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.delUser(4);
sqlSession.commit();
sqlSession.close();
}