Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: which one is better way: saving source or target in many to one association

@Entity
public class Troop {
@OneToMany(mappedBy="troop")
public Set<Soldier> getSoldiers() {
...
}

@Entity
public class Soldier {
@ManyToOne
@JoinColumn(name="troop_fk")
public Troop getTroop() {
...
}

I do something like this:

Troup t = new Troup();
t.getSoldiers().add(soldier);

This saves troop and soldier also. Foreign key is also added since soldier is the owner. But which one is better way, I mean saving toop or soldier using:

Troop t = .....     // Get troop from session
Soldier s = new Soldier();
s.setTroop(t);
like image 519
Ankit Avatar asked Dec 19 '25 02:12

Ankit


1 Answers

You will arrive at the same result with both approaches. However, I suppose that saving individual Soldier entities is a little more efficient:

  • the persistence provider does not need to traverse a collection
  • the code corresponds better to what happens in the DB - only the Soldier table gets updated anyway.

However, perhaps you should think about which business concept fits better, meaning whether are you working with individual Soldiers or with Troops at this point in the application.

  • adding a Soldier to a Troop or
  • assigning a Troop to a Soldier

The difference may be subtle, but depending on you business case either one may be the more readable and comprehensible solution.

like image 83
kostja Avatar answered Dec 20 '25 15:12

kostja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!