溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

mybatis 的mapper 實現(xiàn)

發(fā)布時間:2020-10-24 15:46:42 來源:網(wǎng)絡(luò) 閱讀:331 作者:lifeneedyou 欄目:編程語言

在項目里面,我們經(jīng)常用到mybatis,多年前的hibernate已經(jīng)慢慢被大家所拋棄。自從iteye被收購以后,好久沒有寫博客了,今年是要多寫一些補一補。今天來聊一下mybatis的mapper實現(xiàn)。

   @Component

public interface ActivityMapper {
/**

  • 添加獎品記錄
  • @param prizeEntity
  • @return
    */
    int addGift(PrizeEntity prizeEntity);
/**
 * 添加預約記錄
 * @param activityPrevueEntity
 * @return
 */
int addActivityPrevue(ActivityPrevueEntity activityPrevueEntity);

/**
 * 根據(jù)手機號和活動id獲取該用戶是否預約過
 * @param phone
 * @param activityId
 * @return
 */
int countPrevueByPhoneAndActivityId(@Param("phone")String phone, @Param("activityId")Integer activityId);

}

這是一個比較常見的mapper類的寫法。在xml里面我們需要定義一個和方法名一樣的id.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.vcinema.mapper.ActivityMapper">

<insert id="addGift" parameterType="cn.vcinema.model.PrizeEntity">
    insert into pumpkin_ius.activity_prize_record(user_id, activity_id, prize_code, create_time)
    values(#{userIdInt}, #{activityIdInt}, #{prizeCodeStr}, now())
</insert>

<insert id="addActivityPrevue" parameterType="cn.vcinema.model.ActivityPrevueEntity">
    insert into pumpkin_ius.activity_user_enroll(activity_id, user_id, user_phone, user_name, user_email, create_time)
    values(#{activityId}, #{userId}, #{userPhone}, #{userName}, #{userEmail}, now())
</insert>

<select id="countPrevueByPhoneAndActivityId" resultType="java.lang.Integer">
    select count(*) from pumpkin_ius.activity_user_enroll where user_phone = #{phone} and activity_id = #{activityId}
</select>

</mapper>

在serviceimpl里面,我們通過調(diào)用mapper就可以實現(xiàn)xml 的sql執(zhí)行。

Gift gift = Lottery.lottery(giftList, defaultGift.get(0));
PrizeEntity prizeEntity = setPrizeValue(gift, user.getUserId(), activityId);
// 添加抽獎記錄
activityMapper.addGift(prizeEntity);

需要給MyBatis提供Mapper接口和與之匹配的映射文件,就能夠讓MyBatis按照我們的需求執(zhí)行到對應(yīng)的SQL 這里的實現(xiàn)原理就動態(tài)代理

public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;

public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
}

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if(Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
    } else {
        MapperMethod mapperMethod = this.cachedMapperMethod(method);
        return mapperMethod.execute(this.sqlSession, args);
    }
}

private MapperMethod cachedMapperMethod(Method method) {
    MapperMethod mapperMethod = (MapperMethod)this.methodCache.get(method);
    if(mapperMethod == null) {
        mapperMethod = new MapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration());
        this.methodCache.put(method, mapperMethod);
    }

    return mapperMethod;
}

}

在invoke方法中可以看到,如果我們調(diào)用的是Object中的方法,不做任何處理,直接調(diào)用,否則執(zhí)行:
mapperMethod.execute(this.sqlSession, args);

這里是用jdk的動態(tài)代理來實現(xiàn)了自動調(diào)用。

在開發(fā)的時候,我們有時候不寫xml ,通過注解的形式直接實現(xiàn)調(diào)用,查看例子。

@Component
public interface FeedbackMapper {
int insert(Feedback feedback);

/**
 * 添加用戶意見反饋
 * @param userFeedback
 */
@Insert("  INSERT INTO `pumpkin_ius`.`user_feedback`(`phone`, `device`, `pc_device`, `pc_os`, `pc_channel`, `pc_ip`, `pc_platform`, `pc_version`, `pc_browser_name`, `pc_browser_version`, `play_feedback`, `program_feedback`, `other_feedback`) VALUES (#{phone},#{device},#{pc_device},#{pc_os},#{pc_channel},#{pc_ip},#{pc_platform},#{pc_version},#{pc_browser_name},#{pc_browser_version},#{play_feedback},#{program_feedback},#{other_feedback});")
void addUserFeedback(UserFeedback userFeedback);

}

當然,在SQL復雜的時候,還是寫xml比較方便維護,看起來不那么難受。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI