Spring,JPA:如何使用多对多关系桥表设置查询另一个实体下的实体
Posted
技术标签:
【中文标题】Spring,JPA:如何使用多对多关系桥表设置查询另一个实体下的实体【英文标题】:Spring, JPA: How to query for Entities under another Entity with a many-to-many relationship bridge table setup 【发布时间】:2021-06-28 04:06:54 【问题描述】:我对 Spring 还很陌生。我正在尝试使用此 ERD 查询一位捐赠者下的所有捐赠:
捐助者 |----* 协议 *----|捐赠(使用桥接表的多对多关系)
这是我的代码:
Donor.java
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Donor extends Auditable implements Comparable<Donor>
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Cannot have an empty account number field.")
private String accountNumber;
private String accountName;
private String salutation;
private String donorName;
private String cellphoneNumber;
private String emailAddress;
private String companyTIN;
private String phone1;
private String phone2;
private String faxNumber;
private String address1;
private String address2;
private String address3;
private String address4;
private String address5;
private String companyAddress;
private LocalDate birthDate;
private String notes;
@OneToMany(mappedBy = "donor")
List<MOA> moaList = new ArrayList<>();
...
捐赠.java
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Donation extends Auditable implements Comparable<Donation>
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Cannot have an empty account number field.")
private String accountNumber;
private String accountName;
private String orNumber;
private String date;
private Double amount;
private String notes;
private String needCertificate;
private String purposeOfDonation;
@OneToMany(mappedBy = "donation")
List<MOA> moaList = new ArrayList<>();
...
MOA.java(协议)
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MOA extends Auditable
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "donor_id")
@JsonIgnoreProperties("moaList")
private Donor donor;
@ManyToOne
@JoinColumn(name = "donation_id")
@JsonIgnoreProperties("moaList")
private Donation donation;
private String name;
private String donorAccountNumber;
private Long foreignDonationId;
private LocalDate dateSigned;
在我的 DonorRepository 中,我正在尝试进行此查询,我希望它会给我想要的东西:
public interface DonorRepository extends JpaRepository<Donor, Long>
...
@Query(value = "SELECT * FROM donor WHERE account_number = ?1", nativeQuery = true)
List<Donation> findDonorsDonations(String accountNumber);
...
这给了我一个错误
无法从类型 [java.lang.Object[]] 转换为类型 [com.package.server.domain.Donation] 的值 '1, admin, 2021-04-01 10:29:53.0, admin , 2021-04-01 10:29:53.0, 学校, 123456, null, null, null, null, null, null, null, null, null, John Doe, null, null, null, null, null, Mr. ';嵌套异常是 org
【问题讨论】:
您正在向捐赠者查询,但该方法返回Donation
。
【参考方案1】:
您可以使用规范 api 和 SpecificationExecutor。
您必须加入 MAO 捐赠(MAO with Donor)然后查询特定捐赠者的捐赠。
【讨论】:
以上是关于Spring,JPA:如何使用多对多关系桥表设置查询另一个实体下的实体的主要内容,如果未能解决你的问题,请参考以下文章
Spring Boot JPA多对多关系-Rest Web Service无法返回子对象