1. 程式人生 > 其它 >開啟註解快取_學習筆記--MyBatis(六)註解配置開發

開啟註解快取_學習筆記--MyBatis(六)註解配置開發

技術標籤:開啟註解快取

註解配置,就是使用註解的方式替代對映檔案,在介面方法中使用註解後,無需再寫對映檔案。

常用註解有如下:

@Insert:新增

@Update:更新

@Delete:刪除

@Select:查詢

@Result:結果集封裝

@Results:通常和@Result 一起使用,封裝多個結果集

@ResultMap:呼叫@Results 定義的封裝

@One:一對一結果集封裝

@Many:一對多結果集封裝

@SelectProvider: 動態 SQL 對映

@CacheNamespace:二級快取的使用

1.使用註解實現CRUD

public interface UserDao {

    /**
     * 查詢所有使用者
     * @return
     */
    @Select("select * from user")
    @Results(id = "userMap",    // 指定id供其他方法使用該結果集封裝方式
            value = {
                @Result(id = true, property = "userId", column = "id"),
                @Result(property = "userName", column = "username")
    })
    List<User> findAll();

    /**
     * 根據id查詢使用者
     * @return
     */
    @Select("select * from user where id = #{id}")
    @ResultMap("userMap")
    User findUserById(Integer userId);

    /**
     * 儲存使用者
     * @param user
     * @return
     */
    @Insert("insert into user (username) values (#{userName})")
    @SelectKey(keyProperty = "userId", keyColumn = "id", resultType = Integer.class, before = false, statement = {"select last_insert_id()"})
    int saveUser(User user);

    /**
     * 修改使用者
     * @param user
     * @return
     */
    @Update("update user set username = #{userName} where id = #{userId}")
    int updateUser(User user);

    /**
     * 刪除使用者
     * @param userId
     * @return
     */
    @Delete("delete from user where id = #{id}")
    int deleteUser(Integer userId);

    /**
     * 根據名字模組查詢
     * @param username
     * @return
     */
    @Select("select * from user where username like #{username}")
    @ResultMap("userMap")
    List<User> findUserByName(String username);
}

2.使用註解實現關聯查詢(使用@One和@Many代替association和collection)

/**
 * 使用者持久層介面
 */
public interface UserDao {

    /**
     * 查詢所有使用者
     * @return
     */
    @Select("select * from user")
    @Results(id = "userMap",    // 指定id供其他方法使用該結果集封裝方式
            value = {
                @Result(id = true, property = "userId", column = "id"),
                @Result(property = "userName", column = "username"),
                @Result(property = "userAddress", column = "address"),
                @Result(property = "userSex", column = "sex"),
                @Result(property = "userBirthday", column = "birthday"),
                @Result(column = "id", property = "accounts",
                        many = @Many(select = "com.jodi.dao.AccountDao.findAccountById", fetchType = FetchType.LAZY))
    })
    List<User> findAll();

    /**
     * 根據id查詢使用者
     * @return
     */
    @Select("select * from user where id = #{id}")
    @ResultMap("userMap")
    User findUserById(Integer userId);

}


3.開啟二級快取,只需在主配置檔案開啟二級快取,並且在介面上方新增@CacheNamespace(blocking = true),等同於<cache></cache>

a89b67f9b572087a046ad53a845c35e9.png
mybatisConfig.xml

00c289469f1712208527bd3b82be8ab6.png
UserDao.java(interface)

全文只是個人的筆記,可能沒有太大參考價值,如有錯誤,歡迎大佬指正。