[英]Return Data of two tables using mysql join as one java Object in Spring boot
[英]Java - Spring boot query that return an object made from two different tables
我有兩個通過 id 引用的實體。
一個實體是候選人:
@Entity
@Table(name = "eupass_candidate", schema = "hrast")
public class Candidate{
private long id;
private String firstName;
private String lastName;
private String address;
private String munic;
private String postalCode;
// getters and setters
}
另一個是
@Entity
@Table(name = "eupass_pdffile", schema = "hrast")
public class PDFFile implements Serializable {
private static final long serialVersionUID = -753514667628201960L;
private long id;
private byte[] pdfFile;
private Long idCandidate;
現在我需要連接這兩個表並檢索候選人的名字、姓氏和 pdf(如果有的話)。
我通過以下查詢對此進行了管理:
SELECT fname, lname, pdf_file
FROM hrast.eupass_candidate
LEFT OUTER join hrast.eupass_pdffile
ON (hrast.eupass_candidate.id = hrast.eupass_pdffile.id_candidate)
最后我想將結果保存在一個對象中並將其發送到前端應用程序。
我知道我可以在擴展的 CrudeReopository 中編寫查詢注釋,但在 witch one 中。
這種方法怎么樣?
@Entity
@Table(name = "eupass_pdffile", schema = "hrast")
public class PDFFile implements Serializable {
private static final long serialVersionUID = -753514667628201960L;
private long id;
private byte[] pdfFile;
private Long idCandidate;
//@ManyToMany
@JoinColumn(name="id_candidate") //or whatever your column name is.
private Candidate candidate ;
}
我需要另一個對象嗎?
是的,如@ngueno 在評論中所寫,您需要保存加入結果的 POJO 對象(firstName、lastName、pdfFile)
如果您的要求不是使用 JPA 關系,如果您必須自己管理它,那么您可以在 CandidateRepository 或 PDFFileRespositry 中的任何存儲庫類中編寫查詢。
例如:
import com.example.customquerywithjpa.dto.CandidatePDFFile;
import com.example.customquerywithjpa.entity.Candidate;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CandidateRepository extends JpaRepository<Candidate, Long> {
// Inner Join
@Query("SELECT new com.example.customquerywithjpa.dto.CandidatePDFFile(c.firstName, c.lastName, p.pdfFile) from Candidate c INNER JOIN PDFFile p ON (c.id=p.idCandidate) WHERE c.id =:candidateId")
List<CandidatePDFFile> fetchCandidateAndPDFFIleByCandidateId(@Param("candidateId") long candidateId);
// Left outer join
@Query("SELECT new com.example.customquerywithjpa.dto.CandidatePDFFile(c.firstName, c.lastName, p.pdfFile) from Candidate c LEFT OUTER JOIN PDFFile p ON (c.id=p.idCandidate) WHERE c.id =:candidateId")
List<CandidatePDFFile> fetchCandidateFirstNameLastNameAndItsPDFFileIfExists(@Param("candidateId") long candidateId);
}
為了更好地理解,我創建了示例項目並在假設一名候選人可以擁有零個或多個 pdf 文件的情況下考慮您的用例進行測試。 請參考下面的github存儲庫:
spring-data-jpa-query-that-return-an-custom-objectmade-from-two-different-tables
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.