简体   繁体   中英

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

I have two tables:

A : x_id, emp_id, name, age


B: emp_id, company_id, location

I want to fetch data which contain columns 'x_id', 'emp_id', 'company_id', 'name' joining tables 'A' and 'B' using emp_id..What is the best way to get it?

Is it possible to fetch data without creating beans mapping A and B like Can I create a bean 'Result' containing variables 'x_id', 'emp_id', 'company_id', 'name' and populate it and get list of 'Result' beans as my output?

Yes, first you have to create a model class which includes the required details as the attributes.

   @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;
    }
}

Then, write a custom query in repository class to get required data. Return type will be List of Tuple.

@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();

Finally Map this List of Tuple to List of ResultMap where ever it used in.

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());

resultMapDao is the repository class that findResultMaps() method written in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM