ybatis-CRUD
PPG007 ... 2021-12-28 Less than 1 minute
# ybatis-CRUD
# select
通过 xml 配置:
Tips
- resultMap:返回集。
- resultType:返回类型。
- parameterType:参数类型。
- parameterMap:参数集。
<select id="getUserList" resultMap="userMapper">
select * from usertable;
</select>
1
2
3
2
3
通过注解:
@Select("select * from usertable where id=#{id}")
List<User> test(int id);
1
2
2
# update、insert、delete
注意
若没有开启自动提交,则增删改需要提交事务才能实际修改数据。
开启自动提交:
SqlSessionFactory sqlSessionFactory=MybatisUtil.getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession(true);
1
2
2
若不开启自动提交:
@Insert("insert into usertable(id,username,password) values(#{id},#{username},#{password})")
void addUser(User user);
1
2
2
SqlSessionFactory sqlSessionFactory=MybatisUtil.getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession(false);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
try{
mapper.addUser(new User(32,"zch","password"));
sqlSession.commit();
}
catch (Exception e){
System.out.println("失败");
sqlSession.rollback();
}
sqlSession.close();
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12