I have a OneToMany relationship and Hibernate generates two SELECT queries instead of making a JOIN.
I’m using the following stack (let me know if you need more information):
Blaze Persistence Core + EntityView 1.6.11
Hibernate 6.4.4 final
Spring Boot 3.2.5
I have the following entities:
@Entity
@Table(
uniqueConstraints = {
@UniqueConstraint(name = Truth.UNIQUE_CONSTRAINT_NAME, columnNames = {"slugified_name", "rules_package_id"})
}
)
@NoArgsConstructor @Setter @Getter
public class Truth implements NonCollectableNode {
public static final String UNIQUE_CONSTRAINT_NAME = "UC_truth_name_rules_package_id";
//other fields omitted for brevity
@OneToMany(mappedBy = "truth", fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, orphanRemoval = true)
private List<TruthOption> options = new ArrayList<>();
}
@Entity
@Getter @Setter @NoArgsConstructor
public class TruthOption {
@Id @GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "truth_id", nullable = false)
private Truth truth;
private String summary;
//other fields omitted for brevity
and the following entity views
@EntityView(Truth.class)
public interface TruthResponseView {
@IdMapping
UUID getId();
//other methods omitted for brevity
List<TruthOptionResponseView> getOptions();
}
@EntityView(TruthOption.class)
public interface TruthOptionResponseView {
String getSummary();
}
This is my method in my custom repository implementation.
public Optional<TruthResponseView> findDtoById(UUID id) {
CriteriaBuilder<Truth> criteriaBuilder = criteriaBuilderFactory
.create(entityManager, Truth.class)
.where("id").eq(id);
CriteriaBuilder<TruthResponseView> truthResponseViewCriteriaBuilder = entityViewManager.applySetting(EntityViewSetting.create(TruthResponseView.class), criteriaBuilder);
TruthResponseView truthResponseView;
try {
truthResponseView = truthResponseViewCriteriaBuilder.getSingleResult();
} catch (NoResultException e) {
truthResponseView = null;
}
return Optional.ofNullable(truthResponseView);
}
and the generated queries I see in my console
Hibernate: select t1_0.id,t1_0.canonical_name,t1_0.color,t1_0.dice,t1_0.name,t1_0.replaces,t1_0.rules_package_id,t1_0.slugified_name,t1_0.your_character from truth t1_0 where t1_0.id=?
Hibernate: select o1_0.truth_id,o1_0.id,o1_0.summary from truth_option o1_0 where o1_0.truth_id=?
I don’t really understand what is happening, because I have two other entities that follow a similar association and the query is generated as expected.
I have tried explicitely defining the join for the CriteriaBuilder but it didn’t change anything.
user26464197 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.