Mybatis注解开发
注解开发可以减少编写Mapper映射文件,常用注解如下:
- @Insert:新增
- @Update:更新
- @Delete:删除
- @Select:查询
- @Result:结果集
- @Results:封装多个结果集
- @One:一对一结果集封装
- @Mary:一对多结果集封装
注解开发步骤如下:
- 将mapper.xml中的sql语句分别以注释的方式添加到DAO接口中对应的方法上,如:
public interface UserMapper {
@Select(\"select * from user\")
public List<User> findAll();
@Select(\"select * from user where id=#{id}\")
public User findById(int id);
}
- 修改mybatis配置文件中的映射标签,用package标签替换掉mapper标签,值得注意的是,name属性只需指定到mapper接口所在的包名,不然会出现
Type interface com.rsk.dao.UserMapper is not known to the MapperRegistry
错误
<!--加载映射文件-->
<mappers>
<!--xml开发-->
<!-- <mapper resource=\"com/rsk/mapper/UserMapper.xml\"></mapper>-->
<!--注解开发-->
<package name=\"com.rsk.dao\"/>
</mappers>
- 与xml方式一样,最后构造sqlsesion来动态代理DAO的实现
InputStream resourceAsStream = Resources.getResourceAsStream(\"mybatis-config.xml\");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> all = userMapper.findAll();
User user = userMapper.findById(1);
System.out.println(all);
System.out.println(user.getName());
来源:https://www.cnblogs.com/rskblog/p/16266511.html
本站部分图文来源于网络,如有侵权请联系删除。