I have a requirement where the I receive the values from the Table A. Here Table A stores column details of TableB.
select columnList from TableA => Id1, Id2, Id3, Id4, Id5..
Using the result I need to query from Table B.
Following are the cases
Select Id1, Id2, Id3 from TableB.
Select Id4, Id5 from TableB.
Select Id6, Id7, Id8 from TableB.
Like this case will grow. I would like to know how to achieve this one in Spring Data JPA. It is something like dynamic projections in Spring Data JPA.
Note: Column Names stored in TableA is used in the TableB.
Reason: If I could able to achieve this, it would be easy to pull the data which only what I need.
Need to know, whether we can acheive this in Spring Data JPA or Not? If possible, then how we can.
Can we use CriteriaQuery and CriteriaBuilder.??? Based on the number of column passed, the select query will construct with those values passed in the method call. I can pass that as list and fetch the results from this method call. entityManager.createQuery(criteriaQuery).getResultList();
I need a better solution than this.
public void getTableBValues(final List<String> columnList) {
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createTupleQuery();
final Root<TableB> root = criteriaQuery.from(TableB.class);
// Construct the Selection List to get required columns from TableB
final List<Selection<?>> pathList = columnList.stream().map(p -> {
final Selection<Object> path = root.get(p);
return path;
}).collect(Collectors.toList());
criteriaQuery.multiselect(pathList);
// result will be stored in the result list.
final List<Tuple> resultList = entityManager.createQuery(criteriaQuery).getResultList();
entityManager.close();
}