Reputation: 4829
I have tried 2 different things with hibernate many to many relationship, but i really couldn't find the exact difference between them.
First Scenario :
@Entity
public class Entity1 implements Serializable {
@ManyToMany
List<Entity2> entitiy2;
Second Scenario :
@Entity
public class Entity1 implements Serializable {
@ManyToMany
List<Entity2> entitiy2 = new ArrayList<Entity2>();
Upvotes: 0
Views: 308
Reputation: 692121
For Hibernate, there is no difference. Each time an Entity1 is loaded by Hibernate, its list of Entity2 instances will be initialized (or re-initialized in the second case) with a custom non-null Hibernate list.
For your own code, it does make a difference. With the first case, each time you create an Entity1 instance, it will be in a bad state, with a list of Entity2 instances that is null instead of being empty. Each time you'll want to add a new element to the list of iterate through the list (even in unit tests), you'll have to check before if the list is null or not. The second case is better, since it initializes the object in a good state, where the list is ready to be used.
Upvotes: 4