CURD
1.namespace
namespace中的包名要和Dao/mapper 接口的包名一致
2.select
选择、查询语句
id:就是对应的namespace中的方法名;
resultType:Sql语句执行的返回值;
parameterType:参数类型
2.1编写接口
//查询全部用户
List<User> getUserList();
//根据ID查询用户
User getUserById(int id);
2.2编写对应的mapper中的sql语句
查询所有用户
<select id="getUserList" resultType="com.sophy.pojo.User">
select * from mybatis.user
</select>
查询指定id的用户
<select id="getUserById" parameterType="int" resultType="com.sophy.pojo.User">
select * from mybatis.user where id=#{id};
</select>
2.3测试
@Test
public void getUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
sqlSession.close();
}
3.insert
3.1编写接口
//insert 一个用户
int addUser(User user);
3.2编写对应的mapper中的sql语句
<insert id="addUser" parameterType="com.sophy.pojo.User">
insert into mybatis.user(id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
3.3测试
//曾删改需要提交事物
@Test
public void addUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int addUser = mapper.addUser(new User(4, "哈哈哈", "1234"));
if (addUser>0){
System.out.println("插入成功");
}
//提交事物
sqlSession.commit();
sqlSession.close();
}
4.update
4.1编写接口
int updateUser(User user);
4.2编写对应的mapper中的sql语句
<update id="updateUser" parameterType="com.sophy.pojo.User">
update mybatis.user
set name =#{name} ,pwd=#{pwd}
where id=#{id};
</update>
4.3测试
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
int updateUser = mapper.updateUser(new User(4, "何和阁", "123123"));
if (updateUser>0){
System.out.println("更新成功");
}
sqlSession.commit();
sqlSession.close();
}
5.delete
5.1编写接口
int deleteUser(int user);
5.2编写对应的mapper中的sql语句
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id=#{id};
</delete>
5.3测试
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
mapper.deleteUser(4);
sqlSession.commit();
sqlSession.close();
}
最后,注意点:增删改需要提交事务
sqlSession.commit();