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.uj5u.com/houduan/473426.html
標籤:其他
上一篇:01背包 完全背包
下一篇:JDK8 Stream
