小编pne*_*ior的帖子

Hibernate返回基类的代理

我的域模型中有一个层次结构,由类描述:

@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class BaseEntity {
    @Id
    private Long id;

    // other fields
}

@DiscriminatorValue(value = "Individual")
public class IndividualEntity extends BaseEntity {
    // fields
}

@DiscriminatorValue(value = "Branch")
public class BranchEntity extends BaseEntity {
    // fields
}
Run Code Online (Sandbox Code Playgroud)

我正在获取这样的对象:

Specification<BaseEntity> specification = createSpecification();
BaseEntity entity = baseRepository.findOne(specification);
Run Code Online (Sandbox Code Playgroud)

(我正在使用spring-data)

问题是Hibernate返回代理对象(我理解),但代理是BaseEntity,而不是正确的子类(它的'类是BaseEntity_$$_jvsted9_26,因此entity instanceof IndividualEntity是假的).

有趣的是,并非所有对象都作为代理返回.
我在循环中获取实体(常见事务),其中一些以正常形式(即IndividualEntity/ BranchEntity)返回,一些以代理方式返回.
如果我改变机制,那么每次获取都是在单独的事务中完成的 - 根本不返回任何代理对象.

我知道我可以解开那个代理(例如像这里),但这种行为的原因是什么(对我来说有点奇怪),我可以避免它吗?

java orm hibernate spring-data-jpa

6
推荐指数
1
解决办法
521
查看次数

标签 统计

hibernate ×1

java ×1

orm ×1

spring-data-jpa ×1