-1

I have 2 classes:

@Entity
@Table(name = "users")
public class User {
   //Some fields
   @OneToMany(mappedBy = "user", orphanRemoval = true, cascade = CascadeType.ALL, fetch =       FetchType.EAGER)
    @ToString.Exclude
    @EqualsAndHashCode.Exclude
    private List<Order> orders;
}

And one more:

@Entity
@Table(name = "orders")
public class Order extends BaseEntity{
   // Some fields
   @ManyToOne(optional = false)
   @JoinColumn(name = "user_id", nullable = false)
   private User user;
}

So, my problem that if i try to write new user into database using method persist(), user's(Already become persisted entity with id in persistence context) field orders stays null. And it is a problem when i try to read this field in JSP or update user in database using merge() because of pushing NULL orders field

If i make this.orders = new ArrayList<>(); for every new user, all should be good. If there any possibility not to make initialization of List or do it automatically by Hibernate?

IvanD
  • 1
  • 2
  • Possible duplicate: https://stackoverflow.com/questions/20715143/to-initialize-or-not-initialize-jpa-relationship-mappings – PeterMmm Aug 09 '23 at 16:42
  • @PeterMmm Yes, when i obtain user from db, my collection should be with size 0 and not null. But if i try to update user by using merge()(with orders = null), i got exception: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: ...project.domain.User.orders – IvanD Aug 09 '23 at 16:49
  • A collection with size 0 and `null` are two totally different things. You could initialize the list right in the declaration. Hibernate will not initialize objects for you that are not attached to the database. – cyberbrain Aug 09 '23 at 16:57
  • @cyberbrain OK, I got it, I was just confused by the fact that after the persist() method, the returned entity will have the correct id field. – IvanD Aug 09 '23 at 18:38

0 Answers0