Spring JPA存储库如何编写查询 [英] Spring JPA repository how to write a query

查看:59
本文介绍了Spring JPA存储库如何编写查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个User类(由id标识)和一个Skills类,它具有自己的id字段,并且还引用了User.

I have a User class, that is identified by id, and Skills class, that has its own id field, and also references 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类,并返回一个SoftSkills对象作为结果?

Is there a simple way to write a query, implementing the JPARepository, that would search the SoftSkills class by using user.id field as a parameter and return a SoftSkills object as a result?

推荐答案

您可以从文档中获取:

属性表达式只能引用托管实体的直接属性,如前面的示例所示.在查询创建时,您已经确保了parsed属性是托管域类的属性.但是,您也可以通过遍历嵌套属性来定义约束.假设一个人的地址带有邮政编码.在这种情况下,方法名称为

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);

创建遍历属性x.address.zipCode.解析算法首先将整个部分(AddressZipCode)解释为属性,然后在域类中检查具有该名称的属性(未大写).如果算法成功,它将使用该属性.如果不是,该算法将骆驼箱部分的源从右侧分为头和尾,并尝试找到对应的属性,在我们的示例中为AddressZip和Code.如果算法找到了具有该头部的属性,则该算法将保留该头部的尾部,并继续从该处向下构建树,以刚才描述的方式将尾部向上拆分.如果第一个拆分不匹配,则算法会将拆分点移到左侧(地址,邮政编码)并继续.

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数据JPA文档

这篇关于Spring JPA存储库如何编写查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆