Reputation: 959
I have 2 classes with OneToMany one-directional relationship.
class A {
@Column(name = "a_id")
Integer id;
@OneToMany
@JoinColumn(name = "a_id")
private List<B> listOfB;
//getters and setters
}
class B {
Integer id;
String name;
@Column("a_id")
Integer aId;
//getters and setters
}
In database I already have saved instance of B. I need to do:
a.listOfB.add(b);
save(a);
In object b
in database I have id and name, but fk is null. I need to update fk, but before it I need to fetch object b
;
How can I do it?
Only by writing custom method, or Hibernate/JPA have its own method to fetch objects?
Upvotes: 0
Views: 68
Reputation: 19956
Your mapping is not very common. Common way to have @JoinColumn
in B
and mappedBy = "a"
in A
. And you can specify cascade
. In the simplest case cascade = CascadeType.ALL
.
class A {
@Column(name = "a_id")
Integer id;
@OneToMany(mappedBy = "a", cascade = CascadeType.ALL)
private List<B> listOfB = new ArrayList<B>;
public void addB(B b) {
b.setA(this);
listOfB.add(b);
}
}
class B {
Integer id;
String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "a_id")
private A a;
}
To solve your issue
save(a);
b.setA(a);
saveOrUpdate(b);
And cascade
will help you to do the same by almost your way with a help of addB()
method
a.addB(b);
save(a);
Upvotes: 1