Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

hibernate - JPA Criteria API find by field nested list of entities

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();
question from:https://stackoverflow.com/questions/65916380/jpa-criteria-api-find-by-field-nested-list-of-entities

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...