Update
I'd like to note that @sainr's answer Converting Hibernate proxy to real entity object does solve the problem. But the issue behind the scene is my SiteEntity
having a final
modifier of it's setControllerEntity
and getControllerEntity
, which I didn't raise in my question. And I apologize.
Remove the final
modifier. Then Hibernate can initialize the proxy objects just fine.
The explanation can be found in another answer on Stack Overflow.
I have three entities as following
@Entity
@Table(name = "controller")
public class ControllerEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false, updatable = false)
private long id;
}
@Entity
@Table(name = "site")
public class SiteEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "controller_id", nullable = false)
private ControllerEntity controllerEntity;
}
@Entity
@Table(name = "device")
public class DeviceEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "site_id", nullable = true)
private SiteEntity siteEntity;
}
After I found the device entity, I try to get the controllerEntity
directly from it.
final DeviceEntity deviceEntity1 = deviceRepository.findOne(1L);
System.out.println(deviceEntity1.getSiteEntity().getControllerEntity().getId());
But it results a java.lang.NullPointerException
which is caused by the null
controllerEntity
in the siteEntity
.
Also, even if I tried to use siteRepositoy
to fetch the siteEntity again. the controllerEntity
of it is still null
.
After I removed the fetch = FetchType.LAZY
from both the DeviceEntity and SiteEntity, NPE doesn't happen anymore.
But it seems odd and doesn't make sense. Can I use FetchType.LAZY
while expecting hibernate fetch the correct value?
Thanks.