在休眠状态下使用SINGLE_TABLE继承策略时,如何解决收窄代理警告?

时间:2018-10-28 12:52:50

标签: java hibernate jpa lazy-initialization

我们具有类似波纹管的结构:

@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;
}

BaseEntityBasePersonnelBaseOrganization core_project 中,所有项目都可以使用这些对象。现在,我们创建一个依赖于core_project的项目。我们必须根据我们的业务环境扩展BasePeronnelBaseOrganization。出于这个原因,我们在项目中添加了以下类的一些类:

@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类!

0 个答案:

没有答案