简体   繁体   中英

Saving user info into MySQL using MyBatis

I have problem when saving user info into mysql by using mybatis in my java project. The requirement is below:

If user's info is not exist in database, then insert this user.

If user's info exists in database, then update this user.

Now I have checked the document of mybatis, the dynamic sql defination may save my time, but I didn't find example on it. So below is the sample sql I want to change:

   <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>

Anyone who did this, would you pls give me some lights? thx.

EDIT: Now I can insert or update database based on the filter now. But the problem is that I can't get the return result. Would anyone help? the xml sql below:

  <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>

But after I ran it, it will throw me exception as :

{ "type": "genericResponseWrapper", "httpStatusCode": 500, "applicationErrorCode": 0, "errorMessage": "Unexpected Throwable : Mapper method 'com.rosettastone.ws.ptsws.dao.mybatis.UserLearningCourseDaoImpl.saveOrUpdate' has an unsupported return type: class com.rosettastone.ws.ptsws.domain.UserLearningCourse", "errorDetails": null, "payload": null }

The method I defined in my code is :

    UserLearningCourse saveOrUpdate(UserLearningCourse entity);

I intend to return entity, but error throws. I know the xml sql config is not with return type. but how to resolve?

Finally, I got this solved. First, the sql below:

<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>

Second, the method below:

  UserLearningCourse saveUpdate(UserLearningCourse entity);

Third, Invoke the method:

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

So here, you can see that, the return ID has been automatically filt into the origin userLearningCourse. So here you can directly return the entity now. Because we refered the keyproperty and keycolumn, so it will auto return by mybatis. saveOrUpdate only return affect rows in database.

if you have list of item you may use like below :

 <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM