Issue
I have Certificate
class that contains list of Tag
classes (many to many) and I have to find Certificates
that contain certain Tag
(by tag name)
I'm using JPA Criteria API but cannot do this..
@Entity
@Table(name = "gift_certificate")
public class Certificate {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private BigDecimal price;
private Integer duration;
@Column(name = "create_date")
private LocalDateTime createDate;
@Column(name = "last_update_date")
private LocalDateTime lastUpdateDate;
@ManyToMany
@JoinTable(name = "gift_certificate_tag",
joinColumns = @JoinColumn(name = "tag_id"),
inverseJoinColumns = @JoinColumn(name = "gift_certificate_id")
)
private List<Tag> tags;
getters and setters and other code...
.....
@Entity
@Table(name = "tag")
public class Tag {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
getters and setters and other code...
I tried to do it like this, but I get exception IllegalStateException: Illegal attempt to dereference path source [null.tags] of basic type
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Certificate> query = cb.createQuery(Certificate.class);
Root<Certificate> certificates = query.from(Certificate.class);
certificates.fetch("tags", JoinType.LEFT);
query.select(certificates).distinct(true);
query.where(cb.like(certificates.get("tags").get("name"), params.getTag()));
return entityManager.createQuery(query).getResultList();
Solution
I did this!
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Certificate> criteriaQuery = cb.createQuery(Certificate.class);
Root<Certificate> certificates = criteriaQuery.from(Certificate.class);
Join<Certificate, Tag> tags = certificates.join("tags", JoinType.LEFT);
criteriaQuery = criteriaQuery.distinct(true).where(cb.like(tags.get("name"), params.getTag()));
return entityManager.createQuery(criteriaQuery).getResultList();
Answered By - Igor Tsalko
Answer Checked By - Clifford M. (JavaFixing Volunteer)