简体   繁体   中英

Insert long as NULL into bigint column in PostgreSQL using Java and MyBatis

I have a POJO with a long portNumber field. During instantiation that field defaults to 0 if it is not set. This maps to a nullable and unique column in the database. I'm using mybatis xml for my database layer. How can I insert portNumber as NULL if it is set to 0 ?

I'm using JDBC as the database driver for my PostgreSQL database.

The class

class MyPojo {
    long portNumber;
    long id;

    public MyPojo(long portNumber) {
        this.portNumber = portNumber;
    }
}

The XML insert statement

<insert id="insert" parameterType="MyPojo" useGeneratedKeys="true" keyColumn="primary_key"
        keyProperty="id">
    INSERT INTO some_table (port_number)
    VALUES (#{portNumber})
</insert>
<insert id="insert" parameterType="MyPojo" useGeneratedKeys="true" 
        keyColumn="primary_key" keyProperty="id">
INSERT INTO some_table (port_number)
VALUES (
<dynamic>
    <isEqual property="portNumber" compareValue="0">
    null
</isEqual>
<isNotEqual property="portNumber" compareValue="0">
    #portNumber#    
</isNotEqual>
</dynamic>
)
</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