performing create-or-update with jdbi

2019-05-19 23:12发布

问题:

For a small new project, I decided to give JDBI a try (normally I work with hibernate/jpa).

I like the lightweight, annotation based dao creation using @SqlUpdate/@SqlQuery.

But: There are situations where I can't be sure if I want to create an entity or update an existing one. I would place a "select" statement and depending on its return value use the insert or update statement.

Question: is this somehow supported by the "interface-only" dao in jdbi? Or do I have to write a "createOrUpdate" method myself (making the auto generated dao more or less obsolete)?

Thanks for any hints.

回答1:

Thanks to @zloster I now built a solution based on an abstract class instead of an interface. Works as required.

@SqlUpdate("insert ...")
public abstract void insert(...);

@SqlUpdate("update...")
public abstract void update();

public X createOrUpdate(final X x) {
    if (!exists(x)) {
        insert(x);
    } else {
        update(x);
    }
    return find(...);
}


标签: java jdbi