在父实体的非主键上使用@ManyToOne时遇到一个奇怪的问题。当我获取子实体时,hibernate也会获取父实体,即使它被要求懒惰地获取它,我也没有从父实体查询任何内容。
这是我正在使用的示例实体
属性实体是具有列property_id的父实体,它是非主键。
public class Property extends AbstractEntity implements Serializable {
private static final long serialVersionUID = 8412320472079820864L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
Long id;
@Column(name = "property_id")
public Long propertyId;
@NotNull(message = "Name can't be null")
@Size(max = 100)
@Column(name = "name")
public String name;
现在我有一个Room实体,它通过property_id列与Property实体映射。
public class Room extends AbstractEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
Long id;
@Column(name = "name")
private String name;
@Column(name = "size")
private String size;
@Column(name = "room_type")
private RoomType roomType = RoomType.STANDARD_ROOM;
@ManyToOne(targetEntity = Property.class, fetch = FetchType.LAZY)
@JoinColumn(name = "property_id", referencedColumnName = "property_id", nullable = false)
private Property property;
@Column(name = "priority")
private Integer priority;
现在,当我获取Room hibernate时,它也会点击数据库来获取属性。
有人可以解释我想念的是什么吗?
我尝试实现拦截器仍然没有运气
@ManyToOne(fetch = FetchType.LAZY,optional = false)
@JoinColumn(name = "property_id", referencedColumnName = "property_id", insertable = false, updatable = false)
@LazyToOne(LazyToOneOption.NO_PROXY)
public Property getProperty() {
if (interceptor != null) {
return (Property) interceptor.readObject(this, "property", property);
}
return property;
}
public void setProperty(Property property) {
if (interceptor != null) {
this.property = (Property)interceptor.writeObject(this, "property", this.property, property);
return;
}
this.property = property;
}
P.s:我也尝试使用@NaturalId注释,但是没有用。