raf*_*iss 15 java hibernate jpa join hibernate-annotations
我想使用Hibernate注释来表示使用连接的单向一对多关系.我想在连接上添加一个条件,这样只有当源表中的列("一")等于一个常量值时才会发生这种情况.例如.
SELECT *
FROM buildings b
LEFT JOIN building_floors bf on bf.building_id = b.id AND b.type = 'OFFICE'
Run Code Online (Sandbox Code Playgroud)
我想表示该b.type = 'OFFICE'
查询的一部分.
我的问题与此问题非常相似,只是我在源表上有条件.JPA/Hibernate加入恒定价值
Java实体看起来像这样:
@Entity
@Table(name = "buildings")
public class Building {
@Id
@Column(name = "id")
private int id;
@Column(name = "type")
private String type;
@OneToMany(mappedBy = "buildingId",
fetch = FetchType.EAGER,
cascade = {CascadeType.ALL},
orphanRemoval = true)
@Fetch(FetchMode.JOIN)
// buildings.type = 'OFFICE' ????
private Set<BuildingFloors> buildingFloors;
// getters/setters
}
@Entity
@Table(name = "building_floors")
public class BuildingFloor {
@Id
@Column(name = "building_id")
private int buildingId;
@Id
@Column(name = "floor_id")
private int floorId;
@Column(name = "description")
private String description;
// getters/setters
}
Run Code Online (Sandbox Code Playgroud)
我尝试了一些我有占位符评论的东西:
这不起作用,因为它适用于目标实体.
@JoinColumns({
@JoinColumn(name = "building_id", referencedColumnName = "id"),
@JoinColumn(name = "'OFFICE'", referencedColumnName = "type")
})
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为我得到以下错误(为简洁起见,简化): Syntax error in SQL statement "SELECT * FROM buildings b JOIN building_floors bf on bf.building_id = b.id AND bf.'OFFICE' = b.type"
@JoinColumns({
@JoinColumn(name = "building_id", referencedColumnName = "id"),
@JoinColumn(name = "buildings.type", referencedColumnName = "'OFFICE'")
})
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为在使用单向OneToMany关系时,referencedColumnName来自源表.所以我得到错误:org.hibernate.MappingException: Unable to find column with logical name: 'OFFICE' in buildings
提前致谢!
为什么不使用继承?(我用JPA,我从不直接使用hibernate)
@Entity
@Inheritance
@Table(name = "buildings")
@DiscriminatorColumn(name="type")
public class Building {
@Id
@Column(name = "id")
private int id;
@Column(name = "type")
private String type;
}
Run Code Online (Sandbox Code Playgroud)
而且:
@Entity
@DiscriminatorValue("OFFICE")
public class Office extends Building {
@OneToMany(mappedBy = "buildingId",
fetch = FetchType.EAGER,
cascade = {CascadeType.ALL},
orphanRemoval = true)
private Set<BuildingFloors> buildingFloors;
}
Run Code Online (Sandbox Code Playgroud)