0

So I have two entities:

Person.java

@Entity
@Table(name = "persons")
public class Person {
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @OneToMany(mappedBy="person", cascade = CascadeType.REMOVE)
    @JsonIgnoreProperties("person")
    private Set<Address> addresses;

    //getters and setters

}

Address.java

@Entity
@Table(name = "addresses")
public class Address {
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotNull
    @ManyToOne
    @JoinColumn(name = "person_id", nullable = false)
    @JsonIgnoreProperties("addresses")
    private Person person;
    //getters and setters       
}

And later on in my code I have a personDb object (already saved in database) and then I add Address:

Address address = new Address();
address.setPerson(personDb);
address = addressRepository.save(address);

and now I have address object with person object attached to it but my personDb still doesn't have any addresses attached to it. Even if I try to get it from database once more:

personRepository.findOne(personDb.getId());

I have null where should be set of addresses. I also tried changing my annotation in Person class to something like this:

@OneToMany(mappedBy="person", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)

or changing CascadeType to ALL but nothing helps. What can I do to load addresses to my personDb object after they were added to database?

Hema
  • 988
  • 1
  • 16
  • 38
wwwww
  • 339
  • 3
  • 15

2 Answers2

0

This is not best solution, but try to add also new address to personDB.

Address address = new Address();
address.setPerson(personDb);
personDB.addAddress(address);
personRepo.save(personDB)
sf_
  • 1,138
  • 2
  • 13
  • 28
0

Make sure the person is persisted.

For that make an integration test for it. If you are using Spring, I also suggest you use in-memory db for your tests.

@Transactional
@Test
public void testFindOneAddress(){

// persist the person
Person person = new Person();
...
personRepository.save(person);

// persist the address
Address address = new Address();
address.setPerson(person);
addressRepository.save(address);

// find the persisted person and addresses
Person queryResult= personRepository.findOne(person.getId());
assertNotNull(queryResult);
assertNotNull(queryResult.getAddresses());
assertEquals(1, queryResult.getAddresses().size());
assertEquals(address.getId(), queryResult.getAddresses().get(0).getId());

}

Also make sure you person id column is called "person_id"

public class Person {
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "person_id")
    private Integer id;

take it from there

nuvio
  • 2,555
  • 4
  • 32
  • 58