【问题标题】:Criteria to list of Entityinstance+ExtrafieldEntityinstance+Extrafield 列表的标准
【发布时间】:2011-11-28 11:40:49
【问题描述】:
我很确定这个问题已经在任何地方被问过 - 没有找到答案。
我有一个像这样的简单标准:
s.createCriteria(Human.class).list()
给我一个人类实体实例的结果列表(性别和姓名)。
我可以只在生成的实体实例中添加类似“salutation”的计算(不更改 Human.java)并避免创建二维数组吗?
我知道,这应该是这样一个装饰类的工作,有什么解决方法吗?扩大的实体实例应该扩展人类类!
【问题讨论】:
-
Hibernate SQLQuery 可以实现 - 查找 addEntity() 和 addScalar()。
标签:
hibernate
criteria
hibernate-criteria
【解决方案1】:
不,这不是完全可能的。 Criteria 查询只能返回实体、标量数组或从标量构建的值对象(使用ResultTransformer)。
您可以返回 HumanWithSalutation 对象列表,该列表将包含与人类相同的字段 + 一个额外的称呼,但这些将是值对象,而不是持久对象:对这些对象所做的任何修改都不会像人类实例一样持久化到数据库中。
为此,请创建类:
public class HumanWithSalutation extends Human {
private String salutation;
// getter and setter
}
为其分配一个AliasToBeanResultTransformer(这将使用setter 填充您的所有HumanWithSalutation 对象),并确保该条件有一个投影列表,返回Human + the salutation 的所有字段(别名为“salutation”):
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("id");
projectionList.add(Projections.property("name");
projectionList.add(Projections.property("gender");
projectionList.add(Projections.alias(Projections.sqlProjection(...), "salutation"));
criteria.setProjection(projectionList);
如果您不想要 SQL 投影,您可以在 Java 中的 getSalutation() 方法中实现转换(并删除 setter)。
【解决方案2】:
如果您对 @Formula 渴望获取感到满意,可以将具有 @Formula 映射的属性添加到 Human 类中。
或者如果您需要延迟获取此属性,则在与Human 类相同的表上创建一个额外的实体
@Entity
@Table("HUMAN")
@Immutable
public class HumanWithSalutation extends Human {
@Id
private Long id;
@Formula("(select ...)")
private String salutation;
// getter and setter
}
然后将其从Human 映射到@OneToOne(fetch = FetchType.LAZY) 和@PrimaryKeyJoinColumn。