Java – spring boot extends crudrepository
I'm at @ L_ 301_ 0 @ use hibernate in boot application I am creating a new crudrepository for all my model objects to perform basic crud tasks They look like this:
@Repository public interface FoobarCrudRepo extends CrudRepository<Foobar,Long> { }
But then I always need to do some extra things, such as custom search queries with inequalities I follow this pattern:
@Repository public class FoobarDao { @PersistenceContext EntityManager em; public List<Foobar> findFoobarsByDate(Date date) { String sql = "select fb from Foobar fb where createdDate > :date"; ... return query.getResultList(); } }
My question is, can I combine these two concepts into one class? I try to turn it into an abstract class, as follows:
@Repository public abstract class FoobarCrudRepo extends CrudRepository<Foobar,Long> { @PersistenceContext EntityManager em; public List<Foobar> findFoobarsByDate(Date date) { String sql = "select fb from Foobar fb where createdDate > :date"; ... return query.getResultList(); } }
But spring didn't create a bean for it
How can I do that?
thank you!
Solution
There are many ways to achieve this goal If you really need absolute control, try this
interface FoobarRepositoryCustom{ List<Foobar> findFoobarsByDate(Date date); } interface FoobarRepository extends CrudRepository<Foobar,Long>,FoobarRepositoryCustom public class FoobarRespoitoryImpl implements FoobarRepositoryCustom{ @PersistenceContext private EntityManager em; public List<Foobar> findFoobarsByDate(Date date) { String sql = "select fb from Foobar fb where createdDate > :date"; ... return query.getResultList(); } }
You can also use simpler paths and automatically generate queries for you based on method names In your example, you can add it to your foobarcrudrepo. Spring should do the rest by assuming that foobar has an attribute called createddate
List<Foobar> findByCreatedDateGreaterThan(Date date);
See this for a reference on how spring generates queries based on method names http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query -methods. query-creation