grep
grep

Reputation: 5623

Why entity manager returns me object with null values?

I have spring controller, which calls service layer, and it calls Fao layer.

1) I get User object using EntityManager-s find() method. It retrieves data very well.

2) Each user have one to many relationship with School Object.

@ManyToOne(fetch = FetchType.LAZY, optional=false)
    @JoinColumn(name="SCHOOL_ID", foreignKey = @ForeignKey(name = "FK_USER_SHCOOL"))
    private School school;

3) when I get school from user entity object, hibernate logs me SQL query.

select school0_.id as id1_7_0_, school0_.ADDRESS as ADDRESS2_7_0_, school0_.CITY as CITY3_7_0_, 
school0_.DESCRIPTION as DESCRIPT4_7_0_, school0_.EMAIL as EMAIL5_7_0_, school0_.NAME as NAME6_7_0_, 
school0_.version as version7_7_0_ from SCHOOL school0_ where school0_.id=2

when I run this query in SQL Client, I get reall and correct data!

4) BUT when I get school from user entyty:

School s=user.getSchool() 

It returns School object but it have all values null.

Why values are null? I'm confused. In the log, everything is well. Hibenate logs me correct query too! This query returns data, but using entity manager values are null. What can I do?

If I change LAZY TO EAGER, EVERYTHING WORKS WELL! BUT I DO NOT LIKE THAT OF If I merge() existed school entity it retrieves data. I do not understand why?

Upvotes: 3

Views: 5528

Answers (1)

dogankadriye
dogankadriye

Reputation: 538

Because you define FetchType.LAZY fetching for school column; take a look at FetchType.LAZY and FetchType.EAGER differences from HERE . If you want to get not null school object, there are 2 options:

  1. Change FetchType.LAZY to FetchType.EAGER
  2. When your user object persistent call user.getSchool() inside @Transaction annotated method.

Upvotes: 3

Related Questions