Question

Sorry if this is a very nooby/stupid question, but I was wondering if there was any difference, besides implementation, between defining a query in the repository:

public interface EmployeeRepository<Employee, Integer> {

    @Query("select e from Employee e where e.name like :name")
    public List<Employee> findByName(@Param("name") String name);
}

and defining a query in the entity:

@Entity
@NamedQuery(name="Employee.findByName", query="select e from Employee e where e.name like :name")
public class Employee {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    //...
}

Like are there advantages/disadvantages to either one?

Was it helpful?

Solution

Generally speaking we recommend defining the queries at the repository interface for a very simple reason: it's conceptually closer to the query execution. Also, @Query has a few advanced options when it comes to the additional queries that e.g. need to be triggered to implement pagination.

However, if you want to re-use the query definition on multiple query methods, using a named query is still a reasonable option.

The most important aspect IMO is consistency either among the team or at least per repo. If you start with named queries, don't mix them up with @Query definitions as that might confuse developers or at least make it harder to understand what's going on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top