【发布时间】:2021-07-29 23:22:27
【问题描述】:
我在休眠时遇到了 n + 1 选择问题。我看了很多关于这个主题的文章,但我不明白我的错误是什么。
我的查询:
public interface ClientRepository extends JpaRepository<Client, UUID> {
@Query("SELECT c from Client c LEFT JOIN Subscription s on c.company.id = s.company.id WHERE s.id LIKE '%trial%' order by c.firstName ASC")
List<Client> getAllTrials();
}
订阅实体:
@Entity
public class Subscription implements Serializable {
@Id
private String id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
private Company company;
@NotNull
private OffsetDateTime time;
@NotNull
private SubscriptionStatus status;
//getters and setters + constructors = ...
客户实体:
@Entity
public class Client implements Serializable {
@Id
@GeneratedValue
private UUID id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
private Company company;
@NotBlank
private String firstName;
@NotBlank
private String lastName;
@NotBlank
private String email;
...
公司实体:
@Entity
public class Company implements Serializable {
@Id
@GeneratedValue
private UUID id;
@OneToMany(mappedBy = "company", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
@JsonIgnoreProperties("company")
private List<Client> clients;
@OneToMany(mappedBy = "company", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private List<Subscription> subscriptions = new ArrayList<>();
...
当我尝试获取这些属性时,hibernate 使用了太多查询。
model.addAttribute ("trialUsers", clientService.getAllTrialClients ());
<table>
<thead>
<tr>
<td>Name</td>
<td>Surname</td>
<td>Email</td>
<td>time</td>
<td>id</td>
<td>status</td>
</tr>
</thead>
<tbody>
<tr th:each="client : ${trialUsers}">
<td th:text="${client.firstName}"></td>
<td th:text="${client.lastName}"></td>
<td th:text="${client.email}"></td>
<td th:text="${client.company.subscriptions[0].time}"></td>
<td th:text="${client.company.subscriptions[0].id}"></td>
<td th:text="${client.company.subscriptions[0].status}"></td>
</tr>
</tbody>
</table>
【问题讨论】:
-
您尝试过使用
JOIN FETCH吗?请参阅vladmihalcea.com/n-plus-1-query-problem 了解更多信息。 -
我尝试使用 fetch 但它对我不起作用。
标签: java sql hibernate jpa thymeleaf