Spring-data-aop 多表联查返回自定义结果集
Spring-data-aop 多表联查返回自定义结果集
如果我们有两张表bill
customer
,它俩通过bill.customer_id = customer.id
相关联,它俩对应的实体类分别如下
@Entity
@Table(name = "bill")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Bill {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "customer_id")
private Long customerId;
@Column(name = "bill_no")
private String billNo;
@Column(name = "bill_amount")
private float billAmount;
@Column(name = "bill_date")
private LocalDate billDate;
}
和
@Entity
@Table(name = "customer")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "customer_name")
private String customerName;
@Column(name = "customer_age")
private Integer customerAge;
@Column(name = "customer_account")
private String customerAccount;
@Column(name = "customer_password")
private String customerPassword;
}
现在查询一个结果,包括:账单金额,账单日期,账单ID,用户名 字段,对应自定义类如下
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Content implements Serializable {
private Float billAmount;
private LocalDate billDate;
private Long id;
private String customerName;
}
查询方式如下
@Repository
public interface CustomerRepository extends JpaRepository<Customer,Long> {
@Query("select new com.train.spr.entities.Content(b.billAmount, b.billDate, b.id, c.customerName) " +
" from Bill b " +
" join Customer c on b.customerId = c.id")
List<Content> searchContent();
}
注意
⚠️
多表联查要给每张表加别名,即便是虚表,无论是不是多表联查,我都建议这么做,以免报空指针的错误。在使用JPQL语句时,查询结果一定要写成全类名,而且要用
new
,就像我写的这样new com.train.spr.entities.Content(b.billAmount, b.billDate, b.id, c.customerName)
调用
@Slf4j
@Service
public class CustomerServer {
private final CustomerRepository customerRepository;
@Autowired
public CustomerServer(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
// service层调用
public List<Content> searchContent(){
return customerRepository.searchContent();
}
}
本文来自博客园,作者:勤匠,转载请注明原文链接:https://www.cnblogs.com/JarryShu/articles/18518564
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现