Search code examples
spring-bootjpaspring-data-jpamicroservicesspring-boot-jpa

One To Many Bidirectional relationship implementation postgres SpringBoot


I am seeking the suggestion for implementation of Many-to-One mapping classes and was hoping if anyone could provide me a clear picture.

One to One mapping Scenario: Table foo and Table childfoo Foo has one to many and many to one relationship

Here is the JPA entity implementation I've made so far:

@Entity
@Data
@Table(name = "foo")
public class foo implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "foo_id")
private Integer fooId;


@Column(name="someId")
private Integer someId

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

@OneToMany(mappedBy="foo", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<ChildFoo> userRecords = new HashSet<>();
}

ChildFoo class

@Entity
@Data
@NoArgsConstructor
@EqualsAndHashCode(exclude ="foo")
@Table(name = "childfoo")
public class Childfoo implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -8142203085486540150L;
    
    @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_record_id")
    private Integer childfooId;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "foo_id")
     @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private Foo foo;
    
    @Column(name="child_name")
     private String childName;

   }

I've created a repository for the Foo and child foo to be used in the controller to save the data.

Controller code to add the foo and childfoo:

Foo foo = new Foo();
foo.set...

   ChildFoo childFoo = new ChildFoo();
        childFoo.setChildName("abc");
        childFoo.setFoo(foo);

  childFoo.save(childFoo);

EDIT:

Now I'll need to get the childFoo using the someId and someName value . I tried using the join but was wondering if there is any effective way to write a query in ChildFooRepository/ Foo Repository to pass someId and someName.

I have this query in the childFoo and getting the error:

SELECT cf from schema.child_foo cf join schema.foo f"+""
            + " ON cf.foo_id = f.foo_id"+""
                    + " where f.some_id = :someid AND 
               f.somename= :somename

Shall I be adding this query in the Foo repository and not the child foo repository?


Solution

  • You need to make sure that both Foo and ChildFoo are persisted, and that the bidirectional association is synchronized (so when calling setFoo(foo) on the child you should also add childFoo to the corresponding collection of children on the parent).

    So in your case you will probably also need to call save on the parent.

    (see documentation samples on cascading operations and synchronizing bidirectional associations)