Reputation: 348
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?
Upvotes: 0
Views: 1591
Reputation: 51
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.
Upvotes: 1