MyBatis之注解开发
mybatis常用注解:
@Insert:實(shí)現(xiàn)新增
@Update:實(shí)現(xiàn)更新
@Delete:實(shí)現(xiàn)刪除
@Select:實(shí)現(xiàn)查詢
@Result:實(shí)現(xiàn)結(jié)果集封裝
@Results:可以與@Result 一起使用,封裝多個(gè)結(jié)果集
@ResultMap:實(shí)現(xiàn)引用@Results 定義的封裝
@One:實(shí)現(xiàn)一對(duì)一結(jié)果集封裝
@Many:實(shí)現(xiàn)一對(duì)多結(jié)果集封裝
@SelectProvider: 實(shí)現(xiàn)動(dòng)態(tài) SQL 映射
@CacheNamespace:實(shí)現(xiàn)注解二級(jí)緩存的使用
使用注解完成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);/*** 根據(jù)id查詢用戶* @param userId* @return*/@Select("select * from user where id=#{id} ")User findById(Integer userId);/*** 根據(jù)用戶名稱模糊查詢* @param username* @return*/ // @Select("select * from user where username like #{username} ")@Select("select * from user where username like '%${value}%' ")List<User> findUserByName(String username);/*** 查詢總用戶數(shù)量* @return*/@Select("select count(*) from user ")int findTotalUser(); }@Results、@Result、@ResultMap、@One注解
fetchType=FetchType.EAGER為立即加載,一般用在一對(duì)一
fetchType=FetchType.LAZY為延遲加載,一般用在多對(duì)多
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開啟二級(jí)緩存
開啟二級(jí)緩存后,第一次查詢會(huì)執(zhí)行sql,第二次及以后的查詢都會(huì)從緩存中讀取數(shù)據(jù)
注意:開啟緩存的弊端是數(shù)據(jù)沒有實(shí)時(shí)性,當(dāng)數(shù)據(jù)庫中的數(shù)據(jù)一旦修改,查詢的數(shù)據(jù)還是緩存中的數(shù)據(jù)沒有實(shí)時(shí)性。
總結(jié)
以上是生活随笔為你收集整理的MyBatis之注解开发的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot起步配置和自动配置原
- 下一篇: 解决方案:Unable to creat