Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring JPA通过受限集合查找_Spring_Jpa_Spring Data Jpa - Fatal编程技术网

Spring JPA通过受限集合查找

Spring JPA通过受限集合查找,spring,jpa,spring-data-jpa,Spring,Jpa,Spring Data Jpa,我正在使用SpringHibernate和SpringJPA存储库接口 在我的模型中,我为客户和地址设置了经典的双向一对多和多对一。地址有一个名为“customer”的字段,其中包含customer对象,而customer在一个名为addressBook的字段中有一组地址 //from Address Class @ManyToOne private Customer customer; // from Customer class @OneToMany(fetch = FetchTyp

我正在使用SpringHibernate和SpringJPA存储库接口

在我的模型中,我为客户和地址设置了经典的双向一对多和多对一。地址有一个名为“customer”的字段,其中包含customer对象,而customer在一个名为addressBook的字段中有一组地址

//from Address Class

 @ManyToOne
private Customer customer;

// from Customer class

@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer")
private List<Address> addressBook;

我将在Customer类上提供findAddress方法:

public Address findAddress(Long addressId) {
    if(addressId == null) {
        return null;
    }
    Address matchingAddress = null;
    for(Address address : this.addressBook) {
        if(addressId.equals(address.getId()) {
            matchingAddress = address;
            break;
        }
    }
    return matchingAddress;
}

实际上,最后一个应该是有效的:

 Address address = addressRepository.findByCustomerAndId(customer, addressId);

如果您难以创建存储库方法,可以阅读SpringDataJPA文档。特别是它非常有用。如果您需要在嵌套实体属性上创建查询,您可以按照描述的那样执行。

我不知道您遇到了什么问题。。但是这
地址=customer.getAddressBook().findOne(addressId)错误,请使用存储库…好的,谢谢,我将继续使用此代码。我收到一个错误“找不到局部变量customer”。我以前读过关于JPA嵌套属性的部分,但它似乎适用于查找“具有地址匹配id的客户”的场景,我需要从客户通讯簿中查找地址。JPA看起来真的很不直观,无法通过ORM遍历外键关系有点原始……我在客户的通讯簿中添加了一个地址,并试图保存客户——对我来说似乎是合乎逻辑的,但也没有起作用。无论如何,我会继续尝试这个方法。好的,这个方法有效,语法是:Customer=customerRepository.findOne(customerId);Address Address=addressRepository.findOneByCustomerAndId(客户,地址ID);您也可以使用addressRepository.findByCustomerIdAndId(customerId,addressId)。不确定这个答案,当我已经有两个键值时,迭代所有地址似乎很慢。我只是想避免一个客户修改另一个客户的地址的情况。您只需要一个键(地址ID),因为您已经检索到了该客户。
 Address address = addressRepository.findByCustomerAndId(customer, addressId);