简体   繁体   中英

Spring JDBC Data Driven Update

I have a Spring application with a update API endpoint for a Postgres database. The user can submit information and updates will be reflected in the database. The user only submits what they have to update. For example consider the following object:

class Dog {
    String name;
    int age;
    String breed;
    // Attributes and getters/setters...
}

When the user submits a update request, they only send the information they wish to update, such as only name and breed. I have the following function that updates the database with information:

public void update(String name, int age, String breed, JdbcTemplate template) {
    UpdateBuilder query = new UpdateBuilder();
    query.from("DogTable");
    boolean updated = false;
    if (name != null) {
        query.set("name" + " = '" + name + "'");
        updated = true;
    }
    if (age != null) {
        query.set("age" + " = '" + age + "'");
        updated = true;
    }
    if (breed != null) {
        query.set("breed" + " = '" + breed + "'");
        updated = true;
    }
    // And so on...
    if (updated) {
        query.set("UpdatedTime" + " = '" + new Date() + "'");
    }
    query.where("someKey" + " = '" + someId + "'");

    template.update(query.toString());
}

(The query.set() stuff is just a helper class that builds a query string)

As you can see, this gets messy with all the "is the name given, is the age given?" checks. That leads to my question: Is there a data driven approach to do this? What I would like to be able to do is:

myJdbcTemplate.update(ListOfObjectsToUpdate, "TableName");

Simply, the JDBC template would see what I have provided it, and would proceed to update the provided table with that information. Is this even possible? I realize that building queries using strings is bad, but PreparedStatements don't look much better in code (not to mention, they don't solve this issue).

You can use the COALESCE function for this purpose - add user value as well and existing value and if the user value is not null (intended update) it well be set as the new value.

Similar to this -

UPDATE "user" SET alternate_contact_name = COALESCE(<user value>, alternate_contact_name)

This is a MySQL query but COALESCE works same way in Postgresql

The user value will be set and new value if it is not null. When it is null and original value of column is not null, the original value if picked. If both are null then it doesn't matter.

WIth this you can simply pass all parameters and avoid building query in an untidy way.

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