[英]How to select only specific fields using spring CrudRepository?
How can I select only specific fields from the following class hierarchy? 如何仅从以下类层次结构中选择特定字段?
@Entity
public class MyEntity {
@Id private Long id;
@ManyToOne
@JoinColumn(name="fk_person_id", foreignKey = @ForeignKey(name="fk_person"))
private Person person; //unidirectional
private String fieldA, fieldB, ..field M;
//many more fields and some clobs
}
@Entity
public class Person {
@Id private Long id;
private String firstname;
private String lastname;
}
interface MyEntityRepository extends CrudRepository<MyEntity, Long> {
List<MyEntity> findByIdAndPersonFirstnameAndPersonLastname(long id, String firstname, String lastname);
}
This works perfectly, just the performance is very poor as MyEntity
and also Person
have some fields and associations that I would like to prevent to be fetched in this specific case (eg clob/texts). 这样做效果很好,只是性能非常差,因为
MyEntity
和Person
都有一些字段和关联,我想阻止在这种特定情况下获取(例如clob /文本)。
Question: how can I write this query to find the result set, and just fetch the fields that are absolutely required (let's assume id, fieldA, fieldB
from MyEntity
? 问题:如何编写此查询以查找结果集,只需获取绝对必需的字段(让我们假设来自
MyEntity
id, fieldA, fieldB
?
Use lazy initialization for the non necessary fields: 对非必要字段使用延迟初始化 :
FetchType.LAZY
= Doesn't load the relationships unless explicitly “asked for” via getter FetchType.LAZY
=除非通过getter明确“询问”,否则不加载关系 FetchType.EAGER
= Loads ALL relationships FetchType.EAGER
=加载所有关系 For example, in Person
: 例如,在
Person
:
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="fk_person_id", foreignKey = @ForeignKey(name="fk_person"))
private Person person; //unidirectional
Mark the unwanted fields as lazy (beware of this documented warning though), or create a dedicated class with the properties you want, and use projections in your query: 将不需要的字段标记为惰性(但要注意此文档的警告 ),或者创建具有所需属性的专用类,并在查询中使用投影:
select new com.foo.bar.MyEntityWithFirstNameAndLastName(m.id, person.firstname, person.lastname)
from MyEntity m
join m.person person
where ...
If Person is an often-used entity, and contains large blobs that should rarely be fetched, you should consider storing the blobs in a separate entity, and use a OneToOne lazy association. 如果Person是一个经常使用的实体,并且包含很少被提取的大blob,则应考虑将blob存储在单独的实体中,并使用OneToOne延迟关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.