Finder

io.ebean.Finder is a base class that we can extend to create "finders" for each entity bean. The purpose of "finders" is to group all the queries for the given bean type together in one place rather than have the queries spread out across the cost base.

We don't have to use Finders and when we don't we typically either put queries in the service layer code or use repositories.

Example

public class CustomerFinder extends Finder<Long,Customer> {

  public CustomerFinder() {
    super(Customer.class);
  }

  // Add customer finder methods ...

  public Customer byName(String name) {
    return query().eq("name", name).findOne();
  }

  public List<Customer> findNew() {
    return query().where()
      .eq("status", Customer.Status.NEW)
      .orderBy("name")
      .findList()
  }
}

@Entity
public class Customer extends BaseModel {

  public static final CustomerFinder find = new CustomerFinder();
  ...
 }

Once we have a finder as a field on an entity bean we can then use it via.

Customer rob = Customer.find.byName("Rob");

List<Customer> customers = Customer.find.findNew();

Testing with mocki-ebean

For testing purposes we can use mocki-ebean to replace the finder implementation with a test double. Note that with docker based testing this is rarely used now and instead component testing against real databases (docker based) is used instead.

Finder generation via ebeaninit

We can use the ebeaninit command line tool to generate finders for us (both for Java and Kotlin).

Edit Page