我在ORM的Spring Boot应用程序中将spring-data-jpa与hibernate一起使用。我与OneToOne关系生成N + 1查询时遇到问题,而我不需要获取oneToOne对象。
我的OneToOne关系很容易获取,我尝试将懒惰与获取模式结合使用,但仍然无法获取它仅生成一个查询。
这是实体和查询的代码:
@Entity
@Table(name = "item")
public class Item implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@Column(name = "number")
private String number;
@Column(name = "date")
private LocalDate date;
@OneToOne(mappedBy = "item", fetch = FetchType.EAGER)
@JsonIgnore
private Status status;
}
@Entity
@Table(name = "status")
public class Status implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(unique = true)
private Item item;
}
这是存储库中的查询:
@Query(value = "SELECT * FROM ( SELECT number, MAX(date) AS date FROM item WHERE date < ? GROUP BY number) AS latest_it INNER JOIN item ON item.number = latest_it.number AND item.date = latest_it.date", nativeQuery = true)
List<Item> findLatestByNumberAndDate(LocalDate localDate);
运行查询时,我听到了查询音:
select status0_.id ... from status status0_ left outer join item item1_ on status0_.item_id=item1_.id left outer join status status2_ on item1_.id=status2_.item_id where status0_.item_id=?
我希望看到的只是执行存储库中定义的查询。这个问题确实是性能上的痛苦。
您对此有何暗示?
谢谢