带下划线的 findBy 和不带下划线的 findBy 有什么区别?

What is the difference between findBy with underscore and findBy without it?

例子:有什么区别:

List<UserCompany> findByCompany_IdAndCompany_IsActivated(params)
   and 
List<UserCompany> findByCompanyIdAndCompanyIsActivated(params)

下划线是保留字符,可以让你指向正确的对象来构造jpa查询。它仅用于嵌套对象。例如,如果您想在 Company 对象中的 Address 中通过 ZipCode 进行查询。

可以找到更多信息here

如果您的模型在字段名称方面没有歧义,则没有区别。

List<UserCompany> findByCompanyIdAndCompanyIsActivated(params) -

这首先认为 companyId 和 companyIsActivated 是 UserCompany 中的属性,如果失败则尝试查找它们 然后它认为 UserCompany 有一个字段 Company - 这是另一个 class 并且 Company 有字段 - Id 和 IsActivated 并试图找到它们

哪里有下面的东西

List<UserCompany> findByCompany_IdAndCompany_IsActivated(params)

直接假设 UserCompany 有一个字段 Company - 这是另一个 class 并且 Company 有字段 - Id 和 IsActivated 并试图找到它们

来自 spring 文档

Property expressions :--- Property expressions can refer only to a direct property of the managed entity, as shown in the preceding example. At query creation time you already make sure that the parsed property is a property of the managed domain class. However, you can also define constraints by traversing nested properties. Assume Persons have Addresses with ZipCodes. In that case a method name of

List findByAddressZipCode(ZipCode zipCode); creates the property traversal x.address.zipCode. The resolution algorithm starts with interpreting the entire part (AddressZipCode) as the property and checks the domain class for a property with that name (uncapitalized). If the algorithm succeeds it uses that property. If not, the algorithm splits up the source at the camel case parts from the right side into a head and a tail and tries to find the corresponding property, in our example, AddressZip and Code. If the algorithm finds a property with that head it takes the tail and continue building the tree down from there, splitting the tail up in the way just described. If the first split does not match, the algorithm move the split point to the left (Address, ZipCode) and continues.

Although this should work for most cases, it is possible for the algorithm to select the wrong property. Suppose the Person class has an addressZip property as well. The algorithm would match in the first split round already and essentially choose the wrong property and finally fail (as the type of addressZip probably has no code property). To resolve this ambiguity you can use _ inside your method name to manually define traversal points. So our method name would end up like so:

List findByAddress_ZipCode(ZipCode zipCode);