Difference between defining queries in the repository interface or entity class?

▼魔方 西西 提交于 2019-12-11 13:32:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/25012051/difference-between-defining-queries-in-the-repository-interface-or-entity-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!