1 回答
TA贡献1865条经验 获得超7个赞
JPA 查询
您可以按照下一种方法指示左连接:
@Query("SELECT new com.your.package.dto.UserDetailOrderCountDto(u.firstName, u.lastName, COUNT(o)) "
+ "FROM User u LEFT JOIN u.orders o group by u.firstName, u.lastName")
List<UserDetailOrderCountDto> findUsersAndOrderCount();
只需确保将类属性更改orderCount为 long:
public class UserDetailOrderCountDto {
private String firstName;
private String lastName;
private long orderCount;
public UserDetail() {
}
public UserDetail(String firstName, String lastName, long orderCount) {
this.firstName = firstName;
this.lastName = lastName;
this.orderCount = orderCount;
}
// Getters and setters
}
请注意,这适用于您User班级的以下配置:
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
private Set<Order> orders;
使用本机查询
您可以改用本机查询,因此您可以定义左连接:
@Query(value = "select u.first_name as firstName, u.last_name as lastName, count(o.id) as orderCount from user u left join orders o on u.id = o.user_id group by u.first_name, u.last_name;"
, nativeQuery = true)
List<UserDetailOrderCountDto> findUsersAndOrderCount();
您只需要确保生成的列名称与 bean 的属性名称匹配。
此外,在最新版本的 spring 上,您不需要创建 bean,您可以定义一个接口,然后 spring 创建一个从接口继承的 bean:
public interface UserDetailOrderCountDto {
public String getFirstName();
public String getLastName();
public int getOrderCount();
}
添加回答
举报