user3603632
user3603632

Reputation: 447

JPA/Hibernate cascading persist doesn't work

I have a problem cascading the persist operation to children.

I have a parent and a child class. When I save the parent with one child with a Spring-Data Repository the values of the child are all null or 0.

If I add CascadeType.ALL to the OneToMany-Annotation I get this error: "multiple representations of the same entity are being merged"

@Entity
@Getter
@Setter
public class TestParent {
    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "parent", cascade = {CascadeType.DETACH, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.REMOVE}, orphanRemoval = true)
    private List<TestChild> children;
}

@Entity
@Getter
@Setter
public class TestChild {
    @Id
    @GeneratedValue
    private Long id;

    private int value;

    @ManyToOne
    private TestParent parent;
}

Here is the code to test if saving the objects work:

@Test
@Transactional
public void test123(){
    TestParent parent = new TestParent();
    parent = testRepo.save(parent);

    TestChild child1 = new TestChild();
    child1.setValue(3);
    child1.setParent(parent);
    parent.setChildren(new ArrayList<>());
    parent.getChildren().add(child1);

    parent = testRepo.save(parent);

    assertThat(parent.getChildren().size()).isNotZero();
    assertThat(parent.getChildren().get(0).getValue()).isEqualTo(3);
}

So my approach is to fix cascading the Persist without adding the cascadeType Merge. Any hints what I'm doing wrong?

Upvotes: 0

Views: 2172

Answers (1)

csharpfolk
csharpfolk

Reputation: 4290

First Hibernate User Guide is a great resource if you want to learn something about mapping entities to DB.

I checked your example and it works on my machine (TM) with following repo declaration:

public interface PersonRepository extends CrudRepository<HibernateProxyDemoApplication.TestParent, Long> {  }

And spring boot application:

@SpringBootApplication
@EnableJpaRepositories // just to make sure
public class HibernateProxyDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(HibernateProxyDemoApplication.class, args);
    }
...
}

and pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

I can only suggest to you to first remove Lombok annotations (@Getter/@Setter) and to write getters/setters manually, then to look what may be wrong with your program.

PS. It also works with cascade ALL

Upvotes: 1

Related Questions