Mybatis增删改查
1. 设置mapper.xml
- namespace:namespace中的包名和mapper接口的包名一致!
- id:对应的namespace中的方法名
- resultType:sql语句执行的返回值
- parameterType:参数类型
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Mapper接口-->
<mapper namespace="com.zengwen.dao.UserMapper">
<!--id名为接口的方法名 -->
<select id="getUserList" resultType="com.zengwen.pojo.User">
select * from mybatis.user
</select>
</mapper>
2.select(查询)
2.1编写接口
User getUserById(int id);
2.2编写对应的Mapper
<select id="getUserById" parameterType="int" resultType="com.zengwen.pojo.User">
select * from mybatis.user where id = #{id}
</select>
2.3测试
@Test
public void getUserId(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user.toString());
sqlSession.close();
}
3.insert(添加)
3.1编写接口
int addUser(User user);
3.2编写对应的Mapper
<insert id="addUser" parameterType="com.zengwen.pojo.User" >
insert into mybatis.user(id,name, pwd) values (#{id},#{name},#{pwd})
</insert>
3.3测试
@Test
public void addUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(5,"admin5","123456"));
//提交事务
sqlSession.commit();
sqlSession.close();
}
4.update(更新)
4.1编写接口
int updateUser(User user);
4.2编写对应的Mapper
<update id="updateUser" parameterType="com.zengwen.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id}
</update>
4.3测试
@Test
public void updateUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(5,"admin8","654321"));
//提交事务
sqlSession.commit();
sqlSession.close();
}
5.delete(删除)
5.1编写接口
int deleteUser(int id);
5.2编写对应的Mapper
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id}
</delete>
5.3测试
@Test
public void deleteUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(5);
//提交事务
sqlSession.commit();
sqlSession.close();
}
注意:
- 增删改的操作一定到提交事务——sqlSession.commit();
- 增删改查的操作最后一定到关掉sqlSession——Session.close();