Repositories

Repositories are used to communicate with the underlying database. We won’t need to create a repository for each model. There’s a default implementation, that will be used if no appropriate repository was found which provides basic functionality.

The naming of the repository is important, so that Frogr can find it. Names should start with the model name and end with “Repository” (case-sensitive) and it should extend BaseModelRepository or BaseRelationshipRepository.

If, for example, we want a repository for the Person model, we would create a repository called PersonRepository:

public class PersonRepository extends BaseModelRepository<Person> {
  public void init() {
    Person rick = new Person("Rick Sanchez");
    Person beth = new Person("Beth Smith");
    Person jerry = new Person("Jerry Smith");
    Person morty = new Person("Morty Smith");
    Person summer = new Person("Summer Smith");
    // we need to save the people first, before we can create relationships
    save(rick, beth, jerry, morty, summer);

    rick.setChildren(Arrays.asList(beth));
    beth.setChildren(Arrays.asList(morty, summer));
    jerry.setChildren(Arrays.asList(morty, summer));
    save(rick, beth, jerry, morty, summer);
    MarriedWith marriedWith = new MarriedWith(jerry, beth);
    marriedWith.setYears(10L);
    service().repository(MarriedWith.class).save(marriedWith);
  }
}

We can access our repository easily by calling the .repository(..) method of the Service instance. The method takes either the model class or the name as string. There’s access to it in any REST service class and inside any repository:

@Path("person")
public class Persons extends CRUDService<PersonRepository, Person> {
  @GET
  @Path("init")
  public void init() {
    // insert some data
    try(Transaction tx = service().beginTx()) {
      if(repository().search().count() == 0) {
        repository().init();
        tx.success();
      }
    }
  }
  
  @GET
  @Path("custom-search")
  public List<Person> customSearch(@SearchParam SearchParameter params) {
    try(Transaction ignored = service().beginTx()) {
      return repository().search().params(params).list();
    }
  }
}