Search code examples
javajdbi

How to ignore a property when using @BindBean


I'm using JDBI with this simple query:

@SqlQuery("SELECT id FROM myTable WHERE value = :bean.one")
int search(@BindBean("bean") MyBean bean);

public class Bean { 
  String one; 
  String two; 
  public String getTwo() { throw new IllegalStateException(); }
  // other methods omitted
}

Only the one property is used in the query, so I would expect this to work fine. Unfortunately, the default bean mapper first collects all properties from the bean, and later fills them in the query.

Can I tell JDBI to ignore the bean property or method so it won't be called?


Solution

  • This should be considered a bug (or at least a papercut) in v2--please report it to the team if you'd like it fixed.

    As a workaround, Query.bindFromProperties(bean) will ignore properties that are not in the query. If you rewrite your SQL method as a concrete/default method:

    interface MyDao extends GetHandle {
      default int search(MyBean bean) {
        return getHandle().createQuery(
                "SELECT id FROM myTable WHERE value = :bean.one")
            .bindFromProperties(bean)
            .mapTo(int.class)
            .first();
      }
    }
    

    This has been fixed in the latest v3 alpha, for what it's worth.