我使用Hibernate 5.2.5(如果有問題,也可以使用kotlin和spring 4.3.5),我希望我的類的某些字段能夠被加載。但問題是所有字段都立即加載,我沒有任何特殊的Hibernate設置,都沒有使用Hibernate.initialize()。休眠忽略'lazy'提取類型並立即加載屬性
@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
}
這是我的查詢
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)
}
和輸出:
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=?
請指教我的代碼有什麼問題,以及如何讓Hibernate的加載屬性延遲?謝謝!
[這個答案](http://stackoverflow.com/a/36143746/4754790)提供的替代品時的概述它涉及到懶惰的一對一關聯,其中外鍵位於由子實體映射的表中。 –