Mybatis的開發方式其實有3種:
1. 原始Dao開發(就是把mapper接口、映射文件和實現類都一並開發)
2. xml代理(就是只實現mapper接口和映射文件)
3.注解代理(就是只實現mapper接口,把映射文件的內容通過注解來寫)
注解開發也分3種:
1.靜態SQL
2.動態SQL
3.多表關聯
主要注解有:
靜態:
@Insert:相當於<insert>標簽,實現新增
@Update: 相當於<update>標簽,實現更新
@Delete: 相當於<delete>標簽,實現刪除
@Select: 相當於<select>標簽,實現查詢
@SelectKey:相當於<selectKey>標簽,實現主鍵返回
動態:
@InsertProvider: 相當於<insert>標簽,實現新增
@UpdateProvider: 相當於<update>標簽,實現更新
@DeleteProvider: 相當於<delete>標簽,實現刪除
@SelectProvider: 相當於<select>標簽,實現查詢
多表關聯:
@Results: 相當於<resultMap>標簽,需要和@Result注解一起使用。
@Result: 相當於<result>和<id>標簽,實現結果集中某一列的數據映射
* column 數據庫的列名
* property 需要裝配的屬性名
* one 需要使用的@One 注解(@Result(one=@One()))
* many 需要使用的@Many 注解(@Result(many=@many()))
@One: 相當於<association>標簽,實現一對一關系映射
@Many:相當於<collection>標簽,實現一對多關系映射
@One和@Many注解的屬性:
* select 屬性:代表將要執行的 sql 語句
* fetchType 屬性:代表加載方式,一般如果要延遲加載都設置為 LAZY 的值
使用格式:
1.@Results({@Result(),@Result()})或@Results(@Result())
2.@Result(column=" ",property="",one=@One(select=""))
具體例子:
public interface AnnotationUserMapper { // 查詢 @Select("SELECT * FROM user WHERE id = #{id}") public User findUserById(int id); // 模糊查詢用戶列表 @Select("SELECT * FROM user WHERE username LIKE '%${value}%'") public List<User> findUserList(String username); // 添加並實現主鍵返回 @Insert("INSERT INTO user (username,birthday,sex,address) VALUES (#{username},#{birthday},#{sex},#{address})") @SelectKey(before=false,statement="SELECT LAST_INSERT_ID()",keyProperty="id",resultType=int.class) public void insertUser(User user); // 動態SQL @SelectProvider(type=UserSqlBuilder.class,method="getDynamicSQL") public List<User> dynamicSQL(UserQueryVO vo); // 使用Results注解完成結果映射 @Results({ @Result(column="id",property="id"), @Result(column="username",property="username"), @Result(column="sex",property="sex"), @Result(column="address",property="address") }) @Select("SELECT * FROM user WHERE id = #{id}") public User findUserByIdWithResultMap(int id);
// 演示延遲加載 @Results({ @Result(column="id",property="id"), @Result(column="user_id",property="user_id"), @Result(column="number",property="number"), @Result(column="note",property="note"), @Result(property="user",javaType=User.class,column="user_id",
one=@One(select="com.kkb.mybatis.anno.AnnotationUserMapper.findUserById",fetchType=FetchType.LAZY)) }) @Select("SELECT * FROM orders") public List<OrdersExt> lazyLoading(); class UserSqlBuilder { public String getDynamicSQL(final UserQueryVO vo) { return new SQL() { { SELECT("*"); FROM("user"); User user = vo.getUser(); if (user != null) { if(user.getUsername() != null && !user.equals("")) { WHERE("username like '%"+user.getUsername()+"%'"); } } ORDER_BY("id"); } }.toString(); } } }