有条件地在MyBatis中执行<selectKey>

fub*_*bar 1 mybatis

我有这个问题.只有当提供的bookTypeId为null时,我才需要执行selectKey来为我提供id .可以吗?

这是插入函数映射:

<insert id="insert" parameterType="BookType">
    <selectKey resultType="Integer" keyProperty="bookTypeId" order="BEFORE">
        SELECT nextval('seq_book_type')
    </selectKey>
    INSERT INTO book_type(
        book_type_id,
        book_type_desc
    )
    VALUES(
        #{bookTypeId},
        #{bookTypeDesc}
    )
</insert>
Run Code Online (Sandbox Code Playgroud)

fub*_*bar 6

这毕竟是我做的:

<insert id="insert" parameterType="BookType">
    <selectKey resultType="Integer" keyProperty="bookTypeId" order="BEFORE">
        <if test="bookTypeId == null">SELECT nextval('seq_book_type')</if>
        <if test="bookTypeId != null">SELECT #{bookTypeId}</if>
    </selectKey>
    INSERT INTO book_type(
        book_type_id,
        book_type_desc
    )
    VALUES(
        #{bookTypeId},
        #{bookTypeDesc}
    )
</insert>
Run Code Online (Sandbox Code Playgroud)

它就像一个魅力.请有myBatis经验的人,让我知道是否有比这更好的方法.