MyBatis之注解开发
生活随笔
收集整理的這篇文章主要介紹了
MyBatis之注解开发
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
mybatis常用注解:
@Insert:實現新增
@Update:實現更新
@Delete:實現刪除
@Select:實現查詢
@Result:實現結果集封裝
@Results:可以與@Result 一起使用,封裝多個結果集
@ResultMap:實現引用@Results 定義的封裝
@One:實現一對一結果集封裝
@Many:實現一對多結果集封裝
@SelectProvider: 實現動態 SQL 映射
@CacheNamespace:實現注解二級緩存的使用
使用注解完成CRUD操作:
public interface IUserDao {/*** 查詢所有用戶* @return*/@Select("select * from user")List<User> findAll();/*** 保存用戶* @param user*/@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")void saveUser(User user);/*** 更新用戶* @param user*/@Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")void updateUser(User user);/*** 刪除用戶* @param userId*/@Delete("delete from user where id=#{id} ")void deleteUser(Integer userId);/*** 根據id查詢用戶* @param userId* @return*/@Select("select * from user where id=#{id} ")User findById(Integer userId);/*** 根據用戶名稱模糊查詢* @param username* @return*/ // @Select("select * from user where username like #{username} ")@Select("select * from user where username like '%${value}%' ")List<User> findUserByName(String username);/*** 查詢總用戶數量* @return*/@Select("select count(*) from user ")int findTotalUser(); }@Results、@Result、@ResultMap、@One注解
fetchType=FetchType.EAGER為立即加載,一般用在一對一
fetchType=FetchType.LAZY為延遲加載,一般用在多對多
com.itheima.dao.IUserDao.findById:
@Select("select * from user where id=#{id} ")@ResultMap("userMap")User findById(Integer userId);pojo類的寫法:
@many注解
public interface IUserDao {/*** 查詢所有用戶* @return*/@Select("select * from user")@Results(id="userMap",value={@Result(id=true,column = "id",property = "userId"),@Result(column = "username",property = "userName"),@Result(column = "address",property = "userAddress"),@Result(column = "sex",property = "userSex"),@Result(column = "birthday",property = "userBirthday"),@Result(property = "accounts",column = "id",many = @Many(select = "com.itheima.dao.IAccountDao.findAccountByUid",fetchType = FetchType.LAZY))}) }com.itheima.dao.IAccountDao.findAccountByUid:
@Select("select * from account where uid = #{userId}")List<Account> findAccountByUid(Integer userId);pojo類的寫法:
@CacheNamespace開啟二級緩存
開啟二級緩存后,第一次查詢會執行sql,第二次及以后的查詢都會從緩存中讀取數據
注意:開啟緩存的弊端是數據沒有實時性,當數據庫中的數據一旦修改,查詢的數據還是緩存中的數據沒有實時性。
總結
以上是生活随笔為你收集整理的MyBatis之注解开发的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot起步配置和自动配置原
- 下一篇: 解决方案:Unable to creat