Search code examples
javajdbi

performing create-or-update with jdbi


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.


Solution

  • 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(...);
    }