Question

I have this problem. I need to execute selectKey to provide me with an id only when the supplied bookTypeId is null. Can it be done?

This is the insert function mapping:

<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>
Was it helpful?

Solution

This is what I did after all:

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

It works like a charm. Please anyone with myBatis experience, let me know if there is a better way than this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top