Mybatis-CRUD
1. namespace
namespace中的包名要和实现接口的包名一致
2. select
查询语句;
- id:就是对应的namespace中的方法名;
- resultType:sql语句执行的返回值;(基本类型和引用类型-类)
- parameterType:参数类型;
note:上一篇文章已经讲到如何搭建整个项目,这里我们只改变接口、接口的实现(mapper.xml)和测试类
使用参数类型的示例:
// 根据id查询用户
User getUserById(int id);
<select id="getUserById" parameterType="int" resultType="com.kangzhu.pojo.User">
select * from user where id = #{id}
</select>
@Test
public void testGetUserById() {
// 第一步: 获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 执行
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);
List<User> userList = userMapper.getUserList();
System.out.println(user.getId());
sqlSession.close();
}
3. insert
note:增删改需要提交事务
// insert一个用户
int addUser(User user);
<!-- 对象中的属性可以直接取出来-->
<insert id="addUser" parameterType="com.kangzhu.pojo.User">
insert into user (id, name, password) values (#{id}, #{name}, #{password})
</insert>
@Test
public void testAddUser() {
// 第一步: 获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.addUser(new User(4, "哈哈", "123123"));
// 提交事务
sqlSession.commit();
sqlSession.close();
}
4. update
// 修改用户
int updateUser(User user);
<update id="updateUser" parameterType="com.kangzhu.pojo.User">
update user
set name = #{name}, password = #{password}
where id = #{id};
</update>
@Test
public void testUpdateUser() {
// 第一步: 获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.updateUser(new User(4, "呵呵", "123123"));
// 提交事务
sqlSession.commit();
sqlSession.close();
}
5. delete
// 删除用户
int deleteUser(int id);
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
</delete>
@Test
public void testDeleteUser() {
// 第一步: 获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.deleteUser(4);
// 提交事务
sqlSession.commit();
sqlSession.close();
}