4

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.

Jan Galinski
  • 11,768
  • 8
  • 54
  • 77
  • We need to write method for handling this. – Manikandan Oct 31 '14 at 16:28
  • 1
    So it is not supported ... Who is "we"? – Jan Galinski Nov 02 '14 at 20:29
  • You add an insert() and update() method in the annotated interface DAO. CreateOrUpdate() logic is implemented in the layer above the DAO with select() and if/else. So the answer of your question is: the "CreateOrUpdate" thing is not supported on the interface DAO. – zloster Nov 07 '14 at 18:46
  • 1
    Something came up from the [JDBI's Google user group](https://groups.google.com/forum/?fromgroups#!topic/jdbi/hk0e-7K6VT4). You can use the described solution of abstract class with annotated abstract methods and add concrete implementation for the "createOrUpdate" method. Quite handy IMO. – zloster Nov 08 '14 at 20:29

1 Answers1

5

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(...);
}
Jan Galinski
  • 11,768
  • 8
  • 54
  • 77
  • 1
    A slightly faster variant is to use the update count from the update to check whether the row exists and if not, then insert. if (update(x) == 0) { insert(x); } This spares the exists call. – Tamas Jun 08 '21 at 09:03