Java Spring Data @Query with @OneToMany relation returns no result -
i have following entities:
@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; ...
and following repository interface class:
@repository public interface customerrepository extends crudrepository<customer, long> { @query("select c customer c join c.addresses (a.city = :cityname)") list<customer> findbycity(@param("cityname")string city); }
now, i'm trying run following integration test, fails , absolutely don't know why. unfortunately, i'm beginner spring , i'm trying learn ;-)
@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)); }
the error message is:
java.lang.assertionerror: expected: <1> but: <0>
why result empty. test setting wrong? entity relation? fine, if can me.
you have @onetomany(mappedby = "customer", cascade = cascadetype.all)
on addresses
field in customer
entity. means relationship managed value in customer
field in address
entity.
in test code setting addresses on customer not customer on address. still null, there 2 records in database there no relation. hence nothing returned query.
setting collection setaddresses
bad way of doing things in jpa environment (when on existing instance overwrite persistent collection). remove setaddresses
method , create addaddress
method on customer
instead.
@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, getter returns immutable collection public set<address> getaddresses() { return collections.unmodifiableset(this.addresses); } public void addaddress(address address) { address.setcustomer(this); this.addresses.add(address); } }
this cleans test code little.
@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)); }
Comments
Post a Comment