Spring JPA 存储库如何编写查询

Spring JPA repository how to write a query

我有一个 User class,由 id 标识,Skills class,有自己的 id 字段,还引用 User.

public class User {

    @Id
    @GeneratedValue
    private int id;

    @JsonIgnore
    @OneToOne(mappedBy = "user")
    private SoftSkills softSkills;
}

另一个有

    @Entity
 public class SoftSkills {

    @Id
    @GeneratedValue
    private int id;

    @OneToOne
    @JoinColumn
    private User user;
}

是否有一种简单的方法来编写查询,实现 JPARepository,通过使用 user.id 字段作为参数搜索 SoftSkills class return 结果是一个 SoftSkills 对象?

您可以从文档中获取:

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 a Person has an Address with a ZipCode. In that case a method name of

List<Person> 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.

这样就可以了:

SoftSkills findByUserId(int id);

参考; Spring Data JPA Documentation