bassseo
bassseo

Reputation: 181

Save an entity and all its related entities in a single save in spring boot jpa

I'm using Spring Boot,REST and JPA to build my application. In app, there are 4 entities with one to many relationship.

Is it possible to save multiple entities in one save operation?

Please help!

Parent.java

@Entity
@Data
@NoArgsConstructor 
public class Parent implements Serializable {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private long id;
    private String name;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<ChildA> childA = new ArrayList<>();

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<ChildB> childB = new ArrayList<>();

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private List<ChildC> childC = new ArrayList<>();

    ... getter and setter ...

}

ChildA.java

@Entity
@Data
@NoArgsConstructor
public class ChildA{
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private long id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "parentId")
    private Parent parent;

    private String name;

    public void setParent(Parent parent){
        this.parent = parent;
    }

    ... getter and setter ...
}

ChildB.java and ChildC.java are similar to ChildA.java

Repository.java

@Repository
public interface repository extends JpaRepository<Parent, Long> {

}

I want save this json.

{
  "name": "parent-name",
  "childA": [
    {
      "name": "parent-childA"
    }
  ],
  "childB": [
    {
      "name": "parent-childB"
    }
  ],
  "childC": [
    {
      "name": "parent-childC"
    }
  ]
}

DB

Parent
id   |   name
5        parent-name

ChildA
id   |   parent-id  |  name
 1   |       5      |  parent-childA

ChildB
id   |   parent-id  |  name
 1   |       5      |  parent-childA

ChildC
id   |   parent-id  |  name
 1   |       5      |  parent-childA

Upvotes: 7

Views: 6246

Answers (1)

bassseo
bassseo

Reputation: 181

I found the answer. Thanks for the reply.

@RestController
public class ParentController {
    @Autowired
    private ParentRepository parentRepository;

    @PutMapping("")
    public void save(@RequestBody @Valid Parent parent) {
        parentRepository.save(parent);

    }

Parent.java add @JsonManagedReference

@JsonManagedReference
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<ChildA> childA = new ArrayList<>();

And Child class ChildA.java, ChildB.java, ChildC.java add @JsonBackReference

@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "parentId")
private Parent parent;

Upvotes: 8

Related Questions