Currently, I'm learning about Spring Data JPA, and I found that I need to create a custom interface to make a custom methods. I wonder if someone can explain to me why this is so. Let's say I have entity User
with fields: userId
and name
. Also, I have UserRepository
:
public interface UserRepository extends JpaRepository<User, Long> {...}
I found that I need to make new interface - UserRepositoryCustom
where I should make custom abstract methods. Also, after that, I found that I need to make class UserRepositoryImpl
which implements UserRepositoryCustom
. Let's take a look at the code I made:
@Repository
public class UserRepositoryImpl implements UserRepositoryCustom{
@PersistenceContext
private EntityManager entityManager;
@Override
public List<User> findUserByName(String name) {
Query query = entityManager.createNativeQuery("SELECT em.* FROM User em "
"WHERE em.name = ?1", User.class);
query.setParameter(1, name);
return query.getResultList();
}
}
Can you please explain why I need UserRepositoryCustom
and UserRepositoryImpl
in foreground, And why do I need EntityManager
and @PersistenceContext
above it? Every piece of information is of great importance to me, because that way I will be able to extract what is most important for me, which is to understand.
I found this code, which is working fine, online, but I need to understand it.
CodePudding user response:
You don't need to do this. The direct equivalent would be a method in your UserRepository
interface defined as List<User> findByName(String name)
. You can also use JPA named queries, the @Query
annotation, etc.
The usage of additional interfaces and implementation classes is intended for advanced use cases that are not (easily) possible in the queries Spring Data JPA generates for you based on method names, annotations, etc. It is not intended for easy use cases like the query you show.
And the reason why, is because that is how Spring Data JPA is designed. I highly recommend you read the full Spring Data JPA documentation. You'll notice that the solution in your question is just a minor part of the documentation, which makes clear that this is an escape hatch, not the primary way of using Spring Data JPA.