Skip to content

JPA Repositories

Konstantin Triger edited this page Aug 5, 2019 · 3 revisions

Integration of FluentJPA with Spring JPA Repositories is simple, since FluentJPA.SQL() method is static. The only "external" dependency is on EntityManager, which is required for createQuery() method. Let's see an example:

// EntityManagerSupplier interface is provided by FluentJPA
@Repository
public interface PersonRepository extends CrudRepository<Person, Long>,
                                          EntityManagerSupplier {

    default List<Person> getAllByName(String name) {
        FluentQuery query = FluentJPA.SQL((Person p) -> {
            SELECT(p);
            FROM(p);
            WHERE(p.getName() == name);
        });

        // EntityManager comes from EntityManagerSupplier.getEntityManager()
        return query.createQuery(getEntityManager(), Person.class).getResultList();
    }
}

This is implemented using JPA Repositories custom implementations feature this way:

public class EntityManagerSupplierImpl implements EntityManagerSupplier {
    @PersistenceContext
    private EntityManager em;

    @Override
    public EntityManager getEntityManager() {
        return em;
    }
}

FluentJPA's EntityManagerSupplier implementation supplies a default EntityManager bean. In case a non default EntityManager bean is required use custom implementations feature to supply the EntityManager bean you need.