我在使用Hibernate中的@JoinColumnOrFormula检索嵌入式记录时遇到问题。
嵌入式:
@Embeddable
public class Location implements Serializable {
@Id
@Column(name = "loc_id")
private String id;
@Column(name = "loc_city")
private String city;
@Column(name = "loc_building")
private String building;
@Column(name = "loc_floor")
private String floor;
@Column(name = "loc_room")
private String room;
}
正在使用:
@Entity
@Table(name = "Persons")
public class Person implements Serializable {
...
@ManyToOne
@JoinColumnsOrFormulas({
@JoinColumnOrFormula(formula = @JoinFormula(value = "prs_loc_city", referencedColumnName = "loc_city")),
@JoinColumnOrFormula(formula = @JoinFormula(value = "prs_loc_building", referencedColumnName = "loc_building")),
@JoinColumnOrFormula(formula = @JoinFormula(value = "prs_loc_floor", referencedColumnName = "loc_floor")),
@JoinColumnOrFormula(formula = @JoinFormula(value = "prs_loc_room", referencedColumnName = "loc_room"))})
private Location location = new Location();
...
}
生成正确的Oracle SQL以检索人员的位置:
SELECT
...
FROM PERSONS this_
LEFT OUTER JOIN LOCATIONS location_
ON this_.prs_loc_city = location_.loc_city
AND this_.prs_loc_building = location_.loc_building
AND this_.prs_loc_floor = location_.loc_floor
AND this_.prs_loc_room = location_.loc_room
但是,这适用于提供所有四列的所有情况。 列prs_loc_room为空(null)的人不会从Locations表中检索相应的记录,尽管它存在(loc_room为null)。
正确的SQL工作方式如下:
SELECT
...
FROM PERSONS this_
LEFT OUTER JOIN LOCATIONS location_
ON NVL(this_.prs_loc_city, 'null') = NVL(location_.loc_city, 'null')
AND NVL(this_.prs_loc_building, 'null') = NVL(location_.loc_building, 'null')
AND NVL(this_.prs_loc_floor, 'null') = NVL(location_.loc_floor, 'null')
AND NVL(this_.prs_loc_room, 'null') = NVL(location_.loc_room, 'null')
但是如何使用Hibernate达到这个目标?