I use Hibernate 5.2.5 (also use kotlin and spring 4.3.5 if that matters) and I want some of the fields of my class to be loaded lazily. But the issue is that all fields are loaded immediately, I don't have any special Hibernate settings neither use Hibernate.initialize().
@Entity(name = "task")
@Table(name = "tasks")
@NamedQueries(
NamedQuery(name = "task.findById", query = "SELECT t FROM task AS t WHERE t.id = :id")
)
class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int? = null
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author_id", nullable = false)
lateinit var author: User
@OneToOne(fetch = FetchType.LAZY, mappedBy = "task")
var edit: TaskEdit? = null
}
This is how I query
TaskRepoImpl:
override fun findById(id: Int): Task? {
val task = getCurrentSession().createNamedQuery("task.findById", Task::class.java)
.setParameter("id", id)
.uniqueResult()
return task
}
TaskService:
@Transactional
fun find(id: Int): Task? {
return taskRepo.findById(id)
}
And the output:
Hibernate: select task0_.id as id1_1_, task0_.author_id as author_i3_1_ from tasks task0_ where task0_.id=?
Hibernate: select user0_.id as id1_3_0_, user0_.enabled as enabled2_3_0_, user0_.name as name3_3_0_, user0_.password as password4_3_0_ from users user0_ where user0_.id=?
Hibernate: select taskedit0_.id as id1_0_0_, taskedit0_.task_id as task_id3_0_0_, taskedit0_.text as text2_0_0_ from task_edits taskedit0_ where taskedit0_.task_id=?
Please advice what's wrong with my code and how to make Hibernate load properties lazily? Thank you!