不从关联表中获取数据的JPA Hibernate SQL查询



我正试图使用JPA查询从数据库中获取数据,使用以下查询:

from Candidate c where c.id = :id

where, id = candidate_id(主表主键).

此查询也从其所有关联表中获取数据,而我的要求是仅从其关联表中的2个获取数据。因为第三个表包含大量JSON数据,降低了上述查询的响应时间。

我尝试使用JOIN取JOIN父母的2相关的表,但没有工作。我还在研究如何在获取候选数据时只跳过一列数据(带有重JSON的第三个表的列),但没有运气。

是否有可能实现它使用JPA查询或我需要尝试其他东西?我可以使用repo.save(candidate)一次性保存候选表及其所有关联表的数据,但不想获取其中一个相关表的数据。

下面是我在spring-boot中创建关联的方法:

候选人实体:

@OneToOne(cascade = CascadeType.ALL,                              
fetch = FetchType.LAZY,                                   
mappedBy = "candidate")                                    
@JsonManagedReference                                             
private Address address;                            

@OneToMany(cascade = CascadeType.ALL,                             
fetch = FetchType.LAZY,                                   
mappedBy = "candidate")                                    
@JsonManagedReference                                             
private Set<Skills> skills= new HashSet<>();                    

@OneToMany(cascade = CascadeType.ALL,                             
fetch = FetchType.LAZY,                                   
mappedBy = "candidate")                                    
@JsonManagedReference                                             
private Set<Prefrence> prefrences = new HashSet<>();

解决实体:

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "candidate_id")
@JsonBackReference
private Candidate candidate;

技能实体:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "candidate_id")
@JsonBackReference
private Candidate candidate;
//rest of the fields

首选项实体:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "candidate_id")
@JsonBackReference
private Candidate candidate;
//rest of the fields

我不想在使用candidateRepo.findById(id)时获取偏好实体数据,它应该在获取的候选中始终为空附图图

您需要的是DTO,我认为这是火焰持久实体视图的完美用例。

我创建的库允许JPA模型和自定义接口或抽象类定义模型之间的轻松映射,类似于类固醇上的Spring Data projection。其思想是,您以您喜欢的方式定义您的目标结构(域模型),并通过JPQL表达式将属性(getter)映射到实体模型。

您的用例的DTO模型可以像下面这样使用Blaze-Persistence Entity-Views:

@EntityView(Candidate.class)
public interface CandidateDto {
@IdMapping
Long getId();
String getName();
AddressDto getAddress();
Set<SkillsDto> getSkills();
@EntityView(Address.class)
interface AddressDto {
@IdMapping
Long getId();
String getName();
}
@EntityView(Skills.class)
interface SkillsDto {
@IdMapping
Long getId();
String getName();
}
}

查询是将实体视图应用于查询的问题,最简单的就是通过id进行查询。

CandidateDto a = entityViewManager.find(entityManager, CandidateDto.class, id);

Spring Data集成允许您几乎像Spring Data projection一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

Page<CandidateDto> findAll(Pageable pageable);

最好的部分是,它只会获取实际需要的状态!

最新更新