1

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?

Oliver Drotbohm
  • 80,157
  • 18
  • 225
  • 211
chinesewhiteboi
  • 1,045
  • 1
  • 10
  • 10

1 Answers1

6

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.

Oliver Drotbohm
  • 80,157
  • 18
  • 225
  • 211
  • Thanks Oliver for the response! If you get a chance, could you also take a look at one of my other questions about spring data jpa's paging to confirm the answer I selected? thanks lol [link](http://stackoverflow.com/questions/25008472/pagination-in-spring-data-jpa-limit-and-offset) – chinesewhiteboi Aug 01 '14 at 10:36