Reputation: 41909
Let's say I have Person
and Order
entities in a uni-directional, one-to-many
relationship.
Person
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy = "person")
Set<Order> orders = new HashSet<Order>();
// other fields, constructor, setters and getters
}
Order
@Entity
public class Order {
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "id")
Person person;
// other fields, constructor, setters and getters
}
How can I update a Person
's Set<Order>
with new Order
's?
Do I need to do something like:
Order o = new Order();
// ???
person.setOrders(new HashSet<Order>(o));
Since Person
has a OneToMany
relationship with Order
's, I'm not sure how to set a Person
's orders
.
Upvotes: 3
Views: 5283
Reputation: 9102
Let's say I have Person and Order entities in a uni-directional, one-to-many relationship.
But your mappings suggests otherwise. It's bidirectional relationship with Order class (non-inverse side) having the responsibility of maintaining the relation.
If the relation is bidirectional with Order as non-inverse side, only setting person in Order should be sufficient to reflect the relation in database.
order.setPerson(person);
Although it is highly recommended that you set the Orders in Person as well so that your in-memory representation is consistent with the bidirectional nature of relation. Also recommended is to provide an "adder" method in Person instead of "set" which sets both ends of relationship at one place. For e.g.,
addOrders(Order order){
this.orders.add(order);
order.setPerson(this);
}
Also if you want to actually implement unidirectional one to many you may want to read this discussion.
Upvotes: 2
Reputation: 311
You can do something like this:
person1.getOrder().add(order1);
order1.setPerson(person1);
person1.getOrder().add(order2);
order2.setPerson(person1);
You can use this in loop for multiple orders
Upvotes: 1