bobsyouruncle
bobsyouruncle

Reputation: 137

Updating item created as part of @OneToMany relationship

I'm having problems updating an object created as part of a set in a @OneToMany relationship.

Suppose I've got a very simple domain model, consisting of houses and people who live in those houses:

House:

@Entity
public class House {

    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<Person> persons;

    public void addPerson(Person p) {
        persons.add(p);        

    public Set<Person> getPersons() {
        return persons;
    }

}

Person:

@Entity
public class Person {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    private House house;

}

I've got a Spring Boot JPA repository for House, and a HouseService with the method:

@Transactional
public Person addPerson(Long houseId) {
    House house = houseRepository.findOne(houseId);
    Person person = new Person();
    house.addPerson(person);
    houseRepository.save(house);
    return person;
}

Calling the above method does create a new Person and persist that person in the database, but the returned Person instance doesn't have an ID set (i.e., addPerson().getId() returns null). Can I get the service to return a person instance that does have the ID of the persisted version?

I want to make changes to the Person created using the service's addPerson() method and be able to persist those changes at a later stage.

Upvotes: 1

Views: 96

Answers (2)

Slava Babin
Slava Babin

Reputation: 728

If you want to get id of Person you can create PersonRepository. Like in this questshion.

person = personRepository.save(person);
personRepository.flush();
id=person.getId();

If you want to get person Id before persist, then you must generate id and manually set it.

Upvotes: 1

mhasan
mhasan

Reputation: 3709

In any ORM framework, the persistence of the entity in db is governed by the ORM means there is no guarantee that the entity you called for houseRepository.save(house) will be immediately persisted in database, in case you want such behaviour you have to force your JPA to flush the entity immediately within transaction scope.

For this you will have modify your houseRepository.save method to add the below logic after it calls the entityManager.persist()

Try adding the below code there

entityManager.flush();

I believe Spring boot JPA facilitates flush operation in it, in that case you can directly call it houseRepository.flush() after your persist call.

Upvotes: 0

Related Questions