繁体   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