在存储库接口或实体类中定义查询之间的区别? [英] Difference between defining queries in the repository interface or entity class?
问题描述
抱歉,这是一个非常笨拙/愚蠢的问题,但是我想知道,除了实现之外,在存储库中定义查询之间是否还有其他区别:
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);
}
并在实体中定义查询:
@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?
推荐答案
通常来说,我们建议在存储库接口上定义查询的原因很简单:从概念上讲,它更接近查询执行.另外,对于其他查询,例如@Query
,还有一些高级选项.需要触发才能实现分页.
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.
IMO最重要的方面是团队之间或至少每个回购之间的一致性.如果您从命名查询开始,请不要将它们与@Query
定义混在一起,因为这可能会使开发人员感到困惑,或者至少使它难以理解正在发生的事情.
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.
这篇关于在存储库接口或实体类中定义查询之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!