我有一个小问题。 假设我有这个实体:
import lombok.Data;
import javax.persistence.*;
import java.util.Set;
@Data
@Entity
public class Person {
enum SEX {F, M}
@Id
@GeneratedValue
private Long id;
@OrderBy
@Enumerated(EnumType.STRING)
@ElementCollection(fetch = FetchType.EAGER)
private Set<SEX> sexes;
private String firstName;
private String lastName;
}
因为在某些时候我不想加载名字和姓氏,所以我使用投影( https://docs.spring.io/spring-data/jpa/docs/1.10.2.RELEASE/reference/html/#projections ): 我定义这个接口(interface):
import java.util.Set;
public interface PersonSlim {
String getId();
Set<Person.SEX> getSexes();
}
现在看看这个存储库:
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface PersonRepo extends CrudRepository<Person, Long> {
List<PersonSlim> getAllBy();
}
如果启用 SQL 日志记录 (logging.level.org.hibernate.SQL: DEBUG
) 并执行调用 personRepo.getAllBy();
您将看到:
2018-12-14 16:36:36.808 DEBUG 14227 --- [ main] org.hibernate.SQL : select person0_.id as id1_0_, person0_.first_name as first_na2_0_, person0_.last_name as last_nam3_0_ from person person0_
基本上,Spring 加载所有字段。如果您在 PersonSlim 接口(interface)中排除 getSexes()
方法,Spring 将仅加载 id:
2018-12-14 16:38:03.977 DEBUG 14382 --- [ main] org.hibernate.SQL : select person0_.id as col_0_0_ from person person0_
如果我的投影包含 ElementCollection,Spring 会加载所有字段。
为什么这是一个问题?
我使用带有几何字段的 PostGIS-DB,并且几何图形可能非常大。因此,如果我加载许多实体,它就会变得很慢。在某些情况下,我不想加载此字段。
最佳答案
看来当投影包含非基本类型时,所有列都会包含在查询中。
此处已经存在问题 https://jira.spring.io/browse/DATAJPA-1218 ,从问题上来看,目前还无法通过投影来解决这个问题。
这对您很有用https://github.com/Blazebit/blaze-persistence ,记录在这里Entity Views
它使用与投影类似的实现。
关于java - Spring Data Projection 加载附加字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53783016/