我正在尝试构建一个较小的 SQL,以避免默认为休眠标准构建的“select * from A”。
如果我使用简单的字段(无关系),通过“变形金刚”,我可以设法拥有这个 SQL:
select description, weight from Dog;
嗨,我有这个实体:
@Entity
public class Dog
{
Long id;
String description;
Double weight;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "person_id", nullable = false)
Person owner;
}
@Entity
public class Person
{
Long id;
String name;
Double height;
Date birthDate;
}
我的目标是拥有这个:
select description, weight, owner.name from Dog
我用标准(和子标准)尝试了这个:
Criteria dogCriteria = sess.createCriteria(Dog.class);
ProjectionList proList = Projections.projectionList();
proList.add(Projections.property("description"), description);
proList.add(Projections.property("weight"), weigth);
dogCriteria.setProjection(proList);
Criteria personCriteria = dogCriteria.createCriteria("owner");
ProjectionList ownerProList = Projections.projectionList();
ownerProList.add(Projections.property("name"), description);
dogCriteria.setProjection(ownerProList); //After this line, debugger shows that the
//projection on dogCriteria gets overriden
//and the query fails, because "name" is
//not a field of Dog entity.
我应该如何使用 Projections 来获得更小的 SQL、更少的列?提前致谢。