I am looking into Spring Data JPA. Consider the below example where I will get all the crud and finder functionality working by default and if I want to customize a finder t
As specificed in the documented functionality, the Impl
suffix allows us to have a clean solution:
@Repository
interface, say MyEntityRepository
, either Spring Data methods or custom methodsMyEntityRepositoryImpl
(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:
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 {
// EXAMPLE SPRING DATA METHOD
List findByCommentEndsWith(String x);
List doSomeHql(Long id);
List useTheRepo(Long id);
}
Custom methods implementation bean:
package myapp.infrastructure.myentity;
@Component // Must be @Component !!
public class MyEntityRepositoryImpl { // must have the repo name + Impl !!
@PersistenceContext
private EntityManager entityManager;
@Autowired
private MyEntityRepository myEntityRepository;
@SuppressWarnings("unused")
public List doSomeHql(Long id) {
String hql = "SELECT eFROM MyEntity e WHERE e.id = :id";
TypedQuery query = entityManager.createQuery(hql, MyEntity.class);
query.setParameter("id", id);
return query.getResultList();
}
@SuppressWarnings("unused")
public List useTheRepo(Long id) {
List es = doSomeHql(id);
es.addAll(myEntityRepository.findByCommentEndsWith("DO"));
es.add(myEntityRepository.findById(2L).get());
return es;
}
}
The small 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.)