简体   繁体   中英

Spring-boot JPA entity OneToOne adding new child with relation to parent

I cannot figure out how to simply relate a child entity to and existing parent.

@Entity
@Table(name = "parent")
@Document(indexName = "parent")
public class Parent implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "name")
    private String name;

    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(unique = true)
    private Child child;

    //getters, setters
 }

Child

@Entity
@Table(name = "child")
@Document(indexName = "child")
public class Child implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "name")
    private String name;

    @OneToOne(mappedBy = "child")
    private Parent parent;

    //getters, setters
 }

These are the two basic models.

The parent already exists within the database, and I want to add a new child in relation.

Child childEntity = childRepository.save(child);

The child is populated as follows: child.json

{
   "name": "smallChild", 
   "parent": { "id" : "1" } 
}

I want to be able to save the child, and have it automatically have a relation to the parent.

I did some really nasty code...

  1. Save the Child without a parent for the ID
  2. Query the database for the parent by ID
  3. Set the child to the parent entity
  4. Save the Parent with the new child
  5. Set the Parent entity TO the child entity
  6. Resave the child with the parent.

This ended up being 6-ish database queries.

I tried watching a few course videos from lynda.com, but it didn't help.

Thanks!

Either the Parent Primary Key or the complete entity is required. If the parent's ID available, then the extra query for fetching parent object is not required if the goal is to just save.

If you have the parent's Id available with you then you can save the child entity as:

Child child = new Child();
//...
//Setters for child
//...
//Now just create a parent object and set the id to it
Parent p = new Parent();
p.SetId(parentId); // as the parentId is already vailable
child.setParent(p);
Child childEntity = childRepository.save(child);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM