There's a slightly modified solution that does not require additional interfaces.
As specificed in the documented functionality, the Impl
suffix allows us to have such clean solution:
@Repository
interface, say MyEntityRepository
the custom methods (in addition to your Spring Data methods)MyEntityRepositoryImpl
(the Impl
suffix is the magic) anywhere (doesn't even need to be in the same package) that implements the custom methods only and annotate such class with @Component
** (@Repository
will not work).
MyEntityRepository
via @Autowired
for use in the custom methods.Entity class (for completeness):
package myapp.domain.myentity;
@Entity
public class MyEntity {
@Id private Long id;
@Column private String comment;
}
Repository interface:
package myapp.domain.myentity;
@Repository
public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {
// EXAMPLE SPRING DATA METHOD
List<MyEntity> findByCommentEndsWith(String x);
List<MyEntity> doSomeHql(Long id); // custom method, code at *Impl class below
List<MyEntity> useTheRepo(Long id); // custom method, code at *Impl class below
}
Custom methods implementation bean:
package myapp.infrastructure.myentity;
@Component // Must be @Component !!
public class MyEntityRepositoryImpl { // must have the exact repo name + Impl !!
@PersistenceContext
private EntityManager entityManager;
@Autowired
private MyEntityRepository myEntityRepository;
@SuppressWarnings("unused")
public List<MyEntity> doSomeHql(Long id) {
String hql = "SELECT eFROM MyEntity e WHERE e.id = :id";
TypedQuery<MyEntity> query = entityManager.createQuery(hql, MyEntity.class);
query.setParameter("id", id);
return query.getResultList();
}
@SuppressWarnings("unused")
public List<MyEntity> useTheRepo(Long id) {
List<MyEntity> es = doSomeHql(id);
es.addAll(myEntityRepository.findByCommentEndsWith("DO"));
es.add(myEntityRepository.findById(2L).get());
return es;
}
}
Usage:
// You just autowire the the MyEntityRepository as usual
// (the Impl class is just impl detail, the clients don't even know about it)
@Service
public class SomeService {
@Autowired
private MyEntityRepository myEntityRepository;
public void someMethod(String x, long y) {
// call any method as usual
myEntityRepository.findByCommentEndsWith(x);
myEntityRepository.doSomeHql(y);
}
}
And that's all, no need for any interfaces other than the Spring Data repo one you already have.
The only possible drawbacks I identified are:
Impl
class are marked as unused by the compiler, thus the @SuppressWarnings("unused")
suggestion.Impl
class. (Whereas in the regular fragment interfaces implementation the docs suggest you could have many.)Impl
class at a different package and your test uses only @DataJpaTest
, you have to add @ComponentScan("package.of.the.impl.clazz")
to your test, so Spring loads it.