gpt4 book ai didi

具有@OneToMany关系的Java Spring Data @Query不返回任何结果

转载 作者:搜寻专家 更新时间:2023-11-01 01:16:28 25 4
gpt4 key购买 nike

我有以下实体:

@Entity
public class Customer extends BaseEntity {

private String firstname;
private String lastname;
@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
private Set<Address> addresses;

...

@Entity
public class Address extends BaseEntity {

private String street;
private String houseNumber;
private String zipCode;
private String city;
@ManyToOne
private Customer customer;

...

以及以下存储库接口(interface)类:

@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long> {

@Query("select c from Customer c join c.addresses a where (a.city = :cityName)")
List<Customer> findByCity(@Param("cityName")String city);

}

现在,我正在尝试运行以下集成测试,但它失败了,我完全不知道为什么。不幸的是,我是 Spring 的初学者,我正在努力学习它 ;-)

@Test
public void testFindCustomerByCity() {
Customer customer = new Customer("Max", "Tester");
Address address = new Address("Street", "1", "12345", "City");
HashSet<Address> addresses = new HashSet<Address>();
addresses.add(address);
customer.setAddresses(addresses);
Customer savedCustomer = customerRepository.save(customer);
Assert.assertTrue(savedCustomer.getId() > 0);

List<Customer> customerList = customerRepository.findByCity("City");
Assert.assertThat(customerList.size(), is(1));
}

错误信息是:

java.lang.AssertionError: Expected: is <1> but: was <0>

为什么结果是空的。我的测试设置错了吗?实体关系?没关系,如果你能帮助我。

最佳答案

您可以使用这样的查询方法。使用下划线 (_) 获取子属性。

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
List<Customer> findByAddresses_City(String city);
}

关于具有@OneToMany关系的Java Spring Data @Query不返回任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30643796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com