Browsed by
月份:2018年10月

5.3.4. 使用@Query

5.3.4. 使用@Query

5.3.4. Using @Query 使用命名查询来为实体声明查询,对于小数据量的查询来说个不错的选择。查询本身会绑定被执行的Java方法,你可以使用Spring Data JPA @Query注解,而不是注解在域类上,来绑定对应方法。这种做法将域类从特定持久化信息中释放出来,并协同定位查询所属的库接口。 Using named queries to declare queries for entities is a valid approach and works fine for a small number of queries. As the queries themselves are tied to the Java method that executes them, you can actually bind them directly by using the Spring Data JPA @Query annotation rather than annotating them to the domain class. This frees the domain class from persistence specific information and co-locates the query to the repository interface. 注解在方法上的查询优先级高于使用@NamedQuery定义的查询和在orm.xml声明的命名查询。 Queries ann…

阅读全文 Read More

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> 此查询有一…

阅读全文 Read More

5.3.2. 查询创建

5.3.2. 查询创建

5.3.2. Query Creation JPA的查询创建的机制通常来说都像“查询方法”中描述的一样。下面的例子展示了一个JPA查询方法的转换: Generally, the query creation mechanism for JPA works as described in “Query methods”. The following example shows what a JPA query method translates into: 例52. 从方法名创建查询 Example 52. Query creation from method names public interface UserRepository extends Repository<User, Long> { List<User> findByEmailAddressAndLastname(String emailAddress, String lastname); } 我们使用JPA标准API来创建一个查询,但本质上是被翻译为了:select u from User u where u.emailAddress = ?1 and u.lastname = ?2。Spring Data JPA做了属性检查与属性转换,正如“属性表达式”中描述的一样。 We create a query using the JPA criteria API from this, but, essential…

阅读全文 Read More

5.3.1. 查询策略

5.3.1. 查询策略

5.3.1. Query Lookup Strategies JPA模块支持手动定义一个查询为字符串,或者通过方法命名推导。 The JPA module supports defining a query manually as a String or having it being derived from the method name. 声明查询 Declared Queries 虽然从方法名中推导得到查询的方式比较便捷,但也会面临一个问题,方法名解析器不支持要用到的关键词,或者通过方法名得到的不是预期的结果。所以你可以通过命名规范(请查阅使用JPA命名查询来获取更多信息)来使用JPA命名查询,或者使用@Query(请查询使用@Query获取更新信息)来注解你的查询方法。 Although getting a query derived from the method name is quite convenient, one might face the situation in which either the method name parser does not support the keyword one wants to use or the method name would get unnecessarily ugly. So you can either use JPA named queries through a naming convention (see Usin…

阅读全文 Read More