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?