我有simular(但更長)純SQL查詢:休眠純SQL:二傳手一對一聯接類(實體/表)
.createSQLQuery("
SELECT a.title, ....., b.type_id, b.type_title, c.city_id, c.city_name
FROM articles as a
INNER JOIN content_type as b ON a.type_id=b.type_id
INNER JOIN city_list as c ON a.city_id=c.city_id
WHERE a.id=1")
.addScalar("title")
.....
.setResultTransformer(Transformers.aliasToBean(Article.class))
和一些Java代碼:
@Table(name="articles")
Class Article ... {
...
@Column(name="title")
private String title;
@OneToOne
@JoinColumn(name="type_id")
private ContentType type;
@OneToOne
@JoinColumn(name="city_id")
private Сity city;
...
}
@Table(name="content_type")
Class ContentType ... {
...
@Column(name="type_id")
private Long id;
...
}
@Table(name="city_list")
Class City ... {
...
@Column(name="city_id")
private Long id;
...
}
那麼,我應該如何將它映射到hibernate.createSQLQuery之後呢? 我試過這個,但它不起作用:
.addJoin("b","type")
.addJoin("c","city")
謝謝。
P.S.我需要將這個查詢保存在純sql中,因爲在實際查詢中的「where」塊有一些hibernate無法實現的邏輯。
UPD:執行SQL查詢沒有問題,如何在文章類中定位City和ContentType類是如何映射的。也就是說,當從結果集嘗試訪問ContentType/City(throw Article.getContentType())時,我得到一個NullPoinerException。
可以使用@NativeSqlQuery(//這裏定義你的SQL查詢) –