performing create-or-update with jdbi

2019-05-19 22:45发布

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.

标签: java jdbi
1条回答
对你真心纯属浪费
2楼-- · 2019-05-19 23:20

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(...);
}
查看更多
登录 后发表回答