user6251278
user6251278

Reputation: 23

JPA Parent Child works. Insert child alone

I am new to JPA. I have parent and several children. I am able to successfully save parent and associated child with Column Mapping using below code.

@Data
@Entity
@Table(name = "Parent")
public class Parent{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ParentKey", nullable = false, length = 20)
    private Long parentKey;

    @Column(name = "ParentID", nullable = true, length = 60)
    private String parentID;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "ParentKey", nullable = false)
    private Set<Child> childSet = new HashSet<>(0);
}

@Data
@Entity
@Table(name = "Child")
public class Child {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long childKey;
    private String ChildID;
}

I have a scenario where I receive only child records with parent ID. I lookup parent and want to use same child object and repository for saving additional child records. Since there is no reference for parent key, how can I achieve without duplicating child object.

Child Object does not have ParentKey. I do not want to make any changes to Parent when I am loading child records only.

I am using mySQL.

Thanks

Upvotes: 0

Views: 820

Answers (1)

Yogesh Badke
Yogesh Badke

Reputation: 4587

First, you need a way to query DB that will get you Parent entity by parentID. If you are using spring data jpa module, you can add the following method to a ParentRepository

Optional<Parent> findByParentID(String parentID);

Assuming your service method looks like this, you first retrieve Parent from DB using parentID and then you can add children to that parent.

public void saveChildren(String parentID, Set<Child> children) {
        Parent parent = parentRepository.findByParentID(parentID)
            .orElseThrow(() -> <Your excp that says parent not found by parentID>);

      // assuming you have filtered out duplicates, now you can save remaining as
      parent.getChildSet().addAll(children);
      parentRepository.save(parent);
    }

Upvotes: 1

Related Questions