Tobias Nolte
Tobias Nolte

Reputation: 103

Hibernate ignores constructor and setters

I encountered an odd behavior when I tried to load some Objects from my Database using Hibernate 5.4.3.

Let's say I have a Class A which contains an instance of Class B. Now I want to load Class A from my Database but for some instances of A B is null. To prevent that there are A's with B's that are null I used the code below:

@Entity
public class A{

   @Id
   @GeneratedValue
   private Long id;    

   @OneToOne(cascade = CascadeType.ALL)
   private B b = new B();

   public setB(B b){
       if(b == null){
           this.b = new B();
       }else{
           this.b =b;
       }
   }

   public B getB(){
       return this.b;
   }
}

Now when I use A's somehow I still get A's that have no instance of B. How is this possible?

Upvotes: 0

Views: 754

Answers (1)

Kayaman
Kayaman

Reputation: 73558

Well, business logic in getters / setters is at least dubious, especially if passing a null to a setter results in something as weird as a new blank object being assigned.

Hibernate doesn't need setters to build entities, it can do so with reflection. You can use property access, meaning setters are used, but for this use case I would not do that. Keep your getters / setters clean, and instead go for @PostLoad like XtremeBaumer suggested, or even better, keep them as nulls since that's what they are. I'd be terrified if my database nulls turned into some weird zombie objects on load.

Upvotes: 1

Related Questions