Unidirectional display of OneToMany in Hibernate. Error setting foreign key in reference object

Let's say that there are two objects: parent and child, with a @OneToManymapping from parent to child.

class Parent {
    @Column(name="id")
    private Long id;

    @OneToMany(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id", referencedColumnName = "id")
    private List<Child> children;
}

class Child {
    @Column(name="id")
    private Long id;

    @Column(name="parent_id")
    private Long parentId;
}

As you can see, in my case, the Child table stores the foreign key for the Parent primary key. But I do not want this to be a bi-directional display in my child.

Now there is a problem: I can not set the items parent_idin Child.

I created such instances:

Parent parent = new Parent();
parent.setChildren(Lists.newArrayList(new Child(), new Child()));
parentDomainService.save(parent);

, . , Child. parent_id, Hibernate show_sql. , Child, parent_id is null. .

, . :

Parent parent = new Parent();
parent.setChildren(Lists.newArrayList(new Child(), new Child()));
parent = parentDomainService.save(parent);

for (Child child: parent.getChildren()) {
    child.setParentId(parent.getId());
} 

childDomainService.save(parent.getChildren());

:

org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.somepkg.Child

SO , , , JoinTable. .

? .

P.S.: , , . : 50000 250000 . . join .

, Child. , .

+4
1

,

parent = parentDomainService.save(parent);

" " , , . :

Parent parent = new Parent();
parent = parentDomainService.save(parent);
parent.setChildren(Lists.newArrayList(new Child(), new Child()));

for (Child child: parent.getChildren()) {
    child.setParentId(parent.getId());
} 

childDomainService.save(parent.getChildren());

.

+4

Source: https://habr.com/ru/post/1570753/


All Articles