5.3.3. 使用JPA命名查询

5.3.3. 使用JPA命名查询

5.3.3. Using JPA Named Queries

XML命名查询定义

XML Named Query Definition

可以在classpath下的META-INF文件夹中的orm.xmlJPA配置文件中,添加<named-query />元素来使用XML配置。通过使用名义的命名转换,来启用命名查询的自动调用。下面是详细例子。

To use XML configuration, add the necessary <named-query /> element to the orm.xml JPA configuration file located in the META-INF folder of your classpath. Automatic invocation of named queries is enabled by using some defined naming convention. For more details, see below.

例53. XML命名查询配置

Example 53. XML named query configuration

<named-query name="User.findByLastname">
  <query>select u from User u where u.lastname = ?1</query>
</named-query>

此查询有一个用于实时解析的名称。

The query has a special name that is used to resolve it at runtime.

基于注解的配置

Annotation-based Configuration

基于注解配置的优点是不需要另一个配置文件,降低维护成本。缺点是每当有新的查询声明时,需要重新编译你的域类。

Annotation-based configuration has the advantage of not needing another configuration file to be edited, lowering maintenance effort. You pay for that benefit by the need to recompile your domain class for every new query declaration.

例54. 基于注解的命名查询配置

Example 54. Annotation-based named query configuration

@Entity
@NamedQuery(name = "User.findByEmailAddress", query = "select u from User u where u.emailAddress = ?1")
public class User {

}

声明接口

Declaring Interfaces

需要按如下指定UserRepository,来允许命名查询的执行:

To allow execution of these named queries, specify the UserRepository as follows:

例55. UserRepository中的查询命名声明

Example 55. Query method declaration in UserRepository

public interface UserRepository extends JpaRepository<User, Long> {

  List<User> findByLastname(String lastname);

  User findByEmailAddress(String emailAddress);
}

Spring Data会尝试将这些方法的调用绑定到一个命名查询上,一般是通过域类上配置的名称,名称通过一个点来分割。所以上面例子将使用此例中的命名查询,而不是通过方法名来创建一个查询。

Spring Data tries to resolve a call to these methods to a named query, starting with the simple name of the configured domain class, followed by the method name separated by a dot. So the preceding example would use the named queries defined in the examlpe instead of trying to create a query from the method name.

翻译部分版权归YahaCode团队所有。仅供学习研究之用,任何组织或个人不得私自以此用于任何形式的商业目的

发表评论