簡體   English   中英

通過從兩個表中查詢在 SpringBoot 中獲取數據的最佳方法

[英]Best way to fetch data in SpringBoot by query from two tables

我有兩張桌子:

A : x_id, emp_id, name, age


B: emp_id, company_id, location

我想使用 emp_id 獲取包含“x_id”、“emp_id”、“company_id”、“name”列連接表“A”和“B”的數據。獲取它的最佳方法是什么?

是否可以在不創建映射 A 和 B 的 bean 的情況下獲取數據,例如我可以創建一個包含變量“x_id”、“emp_id”、“company_id”、“name”的 bean“結果”並填充它並獲取“結果”bean 列表作為我的 output?

是的,首先您必須創建一個 model class ,其中包含所需的詳細信息作為屬性。

   @SqlResultSetMapping(
        name = "ResultMap",
        classes = @ConstructorResult(
                targetClass = A.class,
                columns = {
                        @ColumnResult(name = "x_id", type = Long.class),
                        @ColumnResult(name = "emp_id", type = Long.class),
                        @ColumnResult(name = "company_id", type = Long.class),
                        @ColumnResult(name = "name", type = String.class)
                }
        )
)
public class ResultMap {
    private BigInteger x_id;
    private BigInteger emp_id;
    private BigInteger company_id;
    private String name;

    public ResultMap(BigInteger x_id, BigInteger emp_id, BigInteger company_id, String name) {
        this.x_id = x_id;
        this.emp_id = emp_id;
        this.company_id = company_id;
        this.name = name;
    }
}

然后,在存儲庫 class 中編寫自定義查詢以獲取所需數據。 返回類型將是元組列表。

@Query(
        value = "SELECT a.x_id, a.emp_id, b.company_id, a.name \n" +
                "FROM A as a, B as b \n" +
                "WHERE a.emp_id = b.emp_id",
        nativeQuery = true)
List<Tuple> findResultMaps();

最后 Map 這個元組列表到 ResultMap 的列表,它曾經在哪里使用過。

List<Tuple> resultsMapTuples = resultMapDao.findResultMaps();
    List<ResultMap> resultMaps = resultsMapTuples.stream()
            .map(t -> new ResultMap(
                    t.get("x_id", BigInteger.class),
                    t.get("emp_id", BigInteger.class),
                    t.get("company_id", BigInteger.class)
                    t.get("name", String.class)
            )).collect(Collectors.toList());

resultMapDaofindResultMaps()方法寫入的存儲庫 class。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM