簡體   English   中英

使用 MyBatis 將用戶信息保存到 MySQL

[英]Saving user info into MySQL using MyBatis

在我的 java 項目中使用 mybatis 將用戶信息保存到 mysql 時遇到問題。 要求如下:

如果數據庫中不存在用戶的信息,則插入該用戶。

如果數據庫中存在用戶的信息,則更新此用戶。

現在查了mybatis的文檔,動態sql定義可以節省我的時間,但是我沒有找到例子。 所以下面是我要更改的示例 sql:

   <insert id="create" parameterType="UserLearningCourse" >
    <!--If record not exists, perform insert command-->
    INSERT INTO `user_learning_course` (
      user_identifier,
      course_identifier,
      best_grade,
      latest_grade,
      total_number_of_sequences,
      last_modified_at
    )
    VALUES (
      #{user_identifier},
      #{course_identifier},
      #{best_grade},
      #{latest_grade},
      #{total_number_of_sequences},
      #{last_modified_at}
    )
   <!--If record exists, perform update command-->
   UPDATE user_learning_course
    <set>
        <if test="best_grade!=null">
            best_grade                 = #{best_grade},
        </if>
        <if test="latest_grade!=null">
            latest_grade               = #{latest_grade},
        </if>
        <if test="total_number_of_sequences!=null">
            total_number_of_sequences  = #{total_number_of_sequences},
        </if>
        <if test="last_modified_at!=null">
            last_modified_at           = #{last_modified_at},
        </if>
    </set>
    WHERE user_identifier     = #{user_identifier}
</insert>

誰做過這個,你能給我一些燈嗎? 謝謝。

編輯:現在我可以根據過濾器插入或更新數據庫了。 但問題是我無法得到返回結果。 有人會幫忙嗎? 下面的xml sql:

  <insert id="saveOrUpdate" parameterType="UserLearningCourse" useGeneratedKeys="true"
        keyProperty="id" keyColumn="id">
    <selectKey keyProperty="count" resultType="int" order="BEFORE">
        SELECT COUNT(*) count FROM user_learning_course
        where user_identifier = #{userIdentifier}
                AND course_identifier = #{courseIdentifier}
    </selectKey>

    <if test="count > 0">
        UPDATE user_learning_course
        <set>
            <if test="courseIdentifier!=null">
                course_identifier = #{courseIdentifier},
            </if>
            <if test="bestCourseGrade!=null">
                best_grade = #{bestCourseGrade},
            </if>
            <if test="latestCourseGrade!=null">
                latest_grade = #{latestCourseGrade},
            </if>
            <if test="totalNumberOfSequences!=null">
                total_number_of_sequences = #{totalNumberOfSequences},
            </if>
            <if test="lastModifiedAt!=null">
                last_modified_at = #{lastModifiedAt},
            </if>
        </set>
        <where>
                user_identifier = #{userIdentifier}
                AND course_identifier = #{courseIdentifier}
        </where>
    </if>
    <if test="count==0">
        INSERT INTO `user_learning_course` (
        user_identifier,
        course_identifier,
        best_grade,
        latest_grade,
        total_number_of_sequences,
        last_modified_at
        )
        VALUES (
        #{userIdentifier},
        #{courseIdentifier},
        #{bestCourseGrade},
        #{latestCourseGrade},
        #{totalNumberOfSequences},
        #{lastModifiedAt}
        )
    </if>

</insert>

但是在我運行它之后,它會拋出異常:

{ "type": "genericResponseWrapper", "httpStatusCode": 500, "applicationErrorCode": 0, "errorMessage": "Unexpected Throwable : Mapper method 'com.rosettastone.ws.ptsws.dao.mybatis.UserLearningCourseDaoImpl.saveOrUpdate' 有一個不支持的返回類型:class com.rosettastone.ws.ptsws.domain.UserLearningCourse”,“errorDetails”:null,“payload”:null }

我在代碼中定義的方法是:

    UserLearningCourse saveOrUpdate(UserLearningCourse entity);

我打算返回實體,但錯誤拋出。 我知道 xml sql 配置沒有返回類型。 但如何解決?

最后,我解決了這個問題。 首先,下面的sql:

<insert id="saveOrUpdate" parameterType="UserLearningCourse" useGeneratedKeys="true"
    keyProperty="id" keyColumn="id">
<selectKey keyProperty="count" resultType="int" order="BEFORE">
    SELECT COUNT(*) count FROM user_learning_course
    where user_identifier = #{userIdentifier}
            AND course_identifier = #{courseIdentifier}
</selectKey>

<if test="count > 0">
    UPDATE user_learning_course
    <set>
        <if test="courseIdentifier!=null">
            course_identifier = #{courseIdentifier},
        </if>
        <if test="bestCourseGrade!=null">
            best_grade = #{bestCourseGrade},
        </if>
        <if test="latestCourseGrade!=null">
            latest_grade = #{latestCourseGrade},
        </if>
        <if test="totalNumberOfSequences!=null">
            total_number_of_sequences = #{totalNumberOfSequences},
        </if>
        <if test="lastModifiedAt!=null">
            last_modified_at = #{lastModifiedAt},
        </if>
    </set>
    <where>
            user_identifier = #{userIdentifier}
            AND course_identifier = #{courseIdentifier}
    </where>
</if>
<if test="count==0">
    INSERT INTO `user_learning_course` (
    user_identifier,
    course_identifier,
    best_grade,
    latest_grade,
    total_number_of_sequences,
    last_modified_at
    )
    VALUES (
    #{userIdentifier},
    #{courseIdentifier},
    #{bestCourseGrade},
    #{latestCourseGrade},
    #{totalNumberOfSequences},
    #{lastModifiedAt}
    )
</if>

二、方法如下:

  UserLearningCourse saveUpdate(UserLearningCourse entity);

三、調用方法:

 public UserLearningCourse saveUpdate(UserLearningCourse userLearningCourse)
 {
    int affectRows = userLearningCourseDao.saveOrUpdate(userLearningCourse);
    return userLearningCourse;   
 }

所以在這里,你可以看到,返回ID已經自動過濾到源userLearningCourse中。 所以這里你現在可以直接返回實體了。 因為我們引用了keyproperty和keycolumn,所以mybatis會自動返回。 saveOrUpdate 只返回影響數據庫中的行。

如果你有你可以使用的項目列表,如下所示

 <insert id="insertTapAndGoInfo" parameterType="java.util.List">
<foreach collection="list" item="TapAndGo" index="index">
     MERGE  tap_and_go_info as tap
        USING 
        (select 1 as c_temp ) as temp   ON 
        (
        tap.user_id=#{TapAndGo.id.userId} and
        tap.station_code=#{TapAndGo.id.stationCode} and
        tap.article_id=#{TapAndGo.id.articleId}
        )
        WHEN matched then
            UPDATE 
            SET 
                tap.count = #{TapAndGo.count}
        WHEN not matched then
             INSERT  
                 ([user_id]
                 ,[station_code]
                 ,[article_id]
                 ,[product_name]
                 ,[count]
                 ,[label_code]
                 ,[status_update_time]
                 ,[accesspoint_ip_address]
                 ,[accesspoint_mac]
                 ,[modified])
            VALUES
            (
                #{TapAndGo.id.userId},
                #{TapAndGo.id.stationCode},
                #{TapAndGo.id.articleId},
                #{TapAndGo.productName},
                #{TapAndGo.count},
                #{TapAndGo.labelCode},
                #{TapAndGo.statusUpdateTime},
                #{TapAndGo.accesspointIpAddress},
                #{TapAndGo.accesspointMac},
                #{TapAndGo.modified}
            );
 </foreach>
    </insert>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM