我们具有类似波纹管的结构:
@MappedSuperclass
public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
@Override
public boolean equals(Object o) {
if (this == o) return true;
BaseEntity that = (BaseEntity) o;
if (getId() != null ? !getId().equals(that.getId()) : that.getId() != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
}
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "BASE_ORGANIZATION")
@DiscriminatorColumn(name = "disc")
@DiscriminatorValue("baseOrganization")
public class BaseOrganization extends BaseEntity {
@Column(name = "TITLE")
private String title;
}
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "BASE_PERSONNEL")
@DiscriminatorColumn(name = "disc")
@DiscriminatorValue("basePersonnel")
public class BasePersonnel extends BaseEntity {
@Column(name = "FIRSTNAME")
private String firstName;
@Column(name = "LASTNAME")
private String lastName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "BASE_ORGANIZATION_ID")
private BaseOrganization baseOrganization;
}
BaseEntity
,BasePersonnel
和BaseOrganization
在 core_project 中,所有项目都可以使用这些对象。现在,我们创建一个依赖于core_project的项目。我们必须根据我们的业务环境扩展BasePeronnel
和BaseOrganization
。出于这个原因,我们在项目中添加了以下类的一些类:
@Entity
@DiscriminatorValue("organization")
public class Organization extends BaseOrganization {
@Column(name = "MISSION_Type")
private String missionType;
}
@Entity
@DiscriminatorValue("personnel")
public class Personnel extends BasePersonnel {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "MISSION_ORGANIZATION_ID")
private Organization missionOrganization;
}
当我们想招募所有人员时,我们的问题就提出了。当我们在getAllPersonnel
中调用PersonnelRepository
方法时,休眠记录以下信息:
WARN o.h.e.i.StatefulPersistenceContext - HHH000179: Narrowing proxy to class org.xyz.organization.Organization - this operation breaks ==
此后,当我们看到List<Personnel>
对象时,missionOrganization
属性为null
,但超类中的baseOrganization
属性已加载!
我们认为当具有SINGLE_TABLE继承策略的拖类时,休眠LazyInitializer
无法检测到正确的具体类。
我们还调试了narrowProxy
类中的StatefulPersistenceContext
方法,并且我们知道concreteProxyClass.isInstance(proxy)
返回了false
。因为proxy
对象在BaseOrganization
中有LazyInitializer
对象,并且concreteProxyClass
引用了Organization
类!