Sai Kumar
Sai Kumar

Reputation: 112

Join Two Tables using JPA on non-id column using Specification

Is it possible to join two tables on non-primary keys of the Entities, using specification? If yes, Can you please let me know how to do that?

The attribute is of basic type -> Long.

Thanks in advance.

Upvotes: 0

Views: 2371

Answers (1)

Sai Kumar
Sai Kumar

Reputation: 112

Found the answer to the question Hope it helps someone.

Join<PARENT, CHILD> tableJoin = null;   
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<PARENT> criteriaQuery = criteriaBuilder.createQuery(PARENT.class);
Root<PARENT> from = criteriaQuery.from(PARENT.class); 
List<Predicate> predicateList = ByEntityCriteriaHelper.getPredicatesByPatternOnAttributes(entityManager, searchObject, from, criteriaQuery, criteriaBuilder);
Predicate[] predicates = new  Predicate[predicateList.size()];
tableJoin = from.join("CHILD");
predicateList.add(criteriaBuilder.equal(tableJoin.get("id") , searchObject.getChildObject.getId()));
criteriaQuery.where(predicateList.toArray(predicates));
TypedQuery<PARENT> typedQuery =  (TypedQuery<PARENT>)entityManager.createQuery(criteriaQuery);
List<PARENT> resultList = typedQuery.getResultList();

Upvotes: 1

Related Questions