使用MyBatis将用户信息保存到MySQL中

时间:2016-03-01 07:06:40

标签: java mysql mybatis

在我的java项目中使用mybatis将用户信息保存到mysql时遇到问题。要求如下:

如果数据库中不存在用户信息,则插入此用户。

如果用户的信息存在于数据库中,则更新该用户。

现在我检查了mybatis的文件,动态sql defination可以节省我的时间,但我没有找到它的例子。 以下是我想要更改的示例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>

任何人这样做,你会给我一些灯吗? THX。

修改 现在我可以根据过滤器插入或更新数据库了。但问题是我无法得到返回结果。有人会帮忙吗?下面的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方法'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配置没有返回类型。但如何解决?

2 个答案:

答案 0 :(得分:0)

最后,我解决了这个问题。 首先,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仅返回影响数据库中的行。

答案 1 :(得分:0)

如果您有项目列表,则可以按以下方式使用

 <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>
相关问题