I need to search states from StateTable
based on a given country name (not countryId
) in the Country
table which should match the like
SQL operator using JPA criteria API (countryId
is the foreign key in StateTable
as the name implies).
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<StateTable> criteriaQuery = criteriaBuilder
.createQuery(StateTable.class);
Root<StateTable>root=criteriaQuery.from(StateTable.class);
List<Predicate>predicates=new ArrayList<Predicate>();
predicates.add(criteriaBuilder
.like(root.<String>get("countryName"), "%"+countryName+"%"));
criteriaQuery.where(predicates.toArray(new Predicate[0]));
entityManager.createQuery(criteriaQuery)
.setFirstResult(first)
.setMaxResults(pageSize)
.getResultList();
How is the following statement to be modified to fulfill the need? (again countryName
is available in the Country
table and this criteria query is about StateTable
).
predicates.add(criteriaBuilder
.like(root.<String>get("countryName"), "%"+countryName+"%"));
Using JPQL is tedious, since a query needs to be built for multiple search criterion. This is just a demonstration/illustration.
The Country
entity:
@Entity
public class Country implements Serializable {
@Id
private Long countryId; //<----------------------
@Column(name = "country_name")
private String countryName;
@Column(name = "country_code")
private String countryCode;
@OneToMany(mappedBy = "countryId", fetch = FetchType.LAZY)
private Set<StateTable> stateTableSet;
}
The StateTable
entity:
@Entity
public class StateTable implements Serializable {
@Id
private Long stateId;
@Column(name = "state_name")
private String stateName;
@JoinColumn(name = "country_id", referencedColumnName = "country_id")
@ManyToOne(fetch = FetchType.LAZY)
private Country countryId; //<-------------------------------
}