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

时间:2015-06-04 12:25:41

标签: java spring jpa assertion

我有以下实体:

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

}

以下存储库接口类:

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

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

FacebookCallback

错误消息是:

  

java.lang.AssertionError:   预期:是&lt; 1&gt;        但是:是&lt; 0&gt;

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

2 个答案:

答案 0 :(得分:6)

@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)实体的addresses字段中有Customer。这基本上意味着关系由customer实体中Address字段中的值管理。

在您的测试代码中,您只设置客户的地址,而不是地址上的客户。它仍然是null,因此数据库中可能有2条记录,但没有关系。因此,您的查询不会返回任何内容。

像使用setAddresses一样设置集合是一种在JPA环境中执行操作的非常糟糕的方法(当您在已经存在的实例上执行此操作时,您将覆盖持久集合)。移除setAddresses方法并在addAddress上创建Customer方法。

@Entity
public class Customer extends BaseEntity {

    private String firstname;
    private String lastname;

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    private final Set<Address> addresses = new HashSet<Address>();

    // No setter, only a getter which returns an immutable collection
    public Set<Address> getAddresses() {
        return Collections.unmodifiableSet(this.addresses);
    }

    public void addAddress(Address address) {
        address.setCustomer(this);
        this.addresses.add(address);
    }

}

这也会稍微清理一下您的测试代码。

@Test
public void testFindCustomerByCity() {
    Customer customer = new Customer("Max", "Tester");
    customer.addAddress(new Address("Street", "1", "12345", "City"));
    Customer savedCustomer = customerRepository.save(customer);

    Assert.assertTrue(savedCustomer.getId() > 0);

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

答案 1 :(得分:5)

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

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