英文:
How to write criteria query involving an object and another related object of different class?
问题
我的控制器方法
@Override
public List<SuggestedCompnayiesDTO> filterSuggestedCompanies(Long partnerId, Boolean isPharmacy) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<SuggestedCompnayies> query = builder.createQuery(SuggestedCompnayies.class);
Root<SuggestedCompnayies> root = query.from(SuggestedCompnayies.class);
List<Predicate> predicates = new ArrayList<>();
if (partnerId != null) {
predicates.add(builder.equal(companyRepository.findById(root.get("partnerId"), partnerId));
}
// 这一行引发了问题
if (isHospital != null) {
predicates.add(builder.equal(root.get("companyId").get("isHospital"), isHospital));
}
query.select(root).where(builder.and(predicates.toArray(new Predicate[predicates.size()]))).distinct(true);
List<SuggestedCompnayiesDTO> suggestedCompnayiesDTO = suggestedCompnayiesMapper.toDto(em.createQuery(query).getResultList());
return suggestedCompnayiesDTO;
}
在这里,我有一个SuggestedCompanies
类的对象,它包含一个类型为Company
的字段。我的查询需要涉及对这两个对象的条件检查。也就是说,我需要返回只有partnerId
与输入匹配且其内部对象company
的isPharmacy
属性设置为true的SuggestedCompany
对象。
我尝试了以下代码片段
predicates.add(builder.equal(root.get("companyId").get("isHospital"), isHospital));
但我得到错误类型不匹配:无法从Path<Object>转换为Long
。
我该如何解决这个问题?
更新
实体类
public class SuggestedCompnayies implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JsonIgnoreProperties("suggestedByComapnies")
private Partner suggestedBy;
@ManyToOne
@JsonIgnoreProperties("suggestedToComapnies")
private Partner suggestedTo;
@ManyToOne
@JsonIgnoreProperties("suggestedComapnies")
private Company company;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
// 其他属性和方法...
}
公司类
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
// 其他属性和方法...
}
请注意,这只是代码的一部分,包括实体类的一部分属性和方法。如果需要完整的代码,请提供更多上下文。
英文:
My controller method
@Override
public List<SuggestedCompnayiesDTO> filterSuggestedCompanies(Long partnerId, Boolean isPharmacy) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<SuggestedCompnayies> query = builder.createQuery(SuggestedCompnayies.class);
Root<SuggestedCompnayies> root = query.from(SuggestedCompnayies.class);
List<Predicate> predicates = new ArrayList<>();
if (partnerId != null) {
predicates.add(builder.equal(companyRepository.findById(root.get("partnerId"), partnerId));
}
//This line here causes the problem
if (isHospital != null) {
predicates.add(builder.equal(root.get("companyId").get("isHospital")), isHospital));
}
query.select(root).where(builder.and(predicates.toArray(new Predicate[predicates.size()]))).distinct(true);
List<SuggestedCompnayiesDTO> suggestedCompnayiesDTO = suggestedCompnayiesMapper.toDto(em.createQuery(query).getResultList());
return suggestedCompnayiesDTO;
}
}
Here I have an object of class SuggestedCompanies
and it contains a field of type Company
.My query need to involve checking conditions on both these objects.Ie I need to return only SuggestedCompany
objects whose partnerId
matches with the input and its inner object company's isPharmacy
attribute set to true.
I tried following piece of code
predicates.add(builder.equal(root.get("companyId").get("isHospital")), isHospital));
But I get the error Type mismatch: cannot convert from Path<Object> to Long
How can I solve this problem?
Update
Entity Classes
public class SuggestedCompnayies implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JsonIgnoreProperties("suggestedByComapnies")
private Partner suggestedBy;
@ManyToOne
@JsonIgnoreProperties("suggestedToComapnies")
private Partner suggestedTo;
@ManyToOne
@JsonIgnoreProperties("suggestedComapnies")
private Company company;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Partner getSuggestedBy() {
return suggestedBy;
}
public SuggestedCompnayies suggestedBy(Partner partner) {
this.suggestedBy = partner;
return this;
}
public void setSuggestedBy(Partner partner) {
this.suggestedBy = partner;
}
public Partner getSuggestedTo() {
return suggestedTo;
}
public SuggestedCompnayies suggestedTo(Partner partner) {
this.suggestedTo = partner;
return this;
}
public void setSuggestedTo(Partner partner) {
this.suggestedTo = partner;
}
public Company getCompany() {
return company;
}
public SuggestedCompnayies company(Company company) {
this.company = company;
return this;
}
public void setCompany(Company company) {
this.company = company;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SuggestedCompnayies)) {
return false;
}
return id != null && id.equals(((SuggestedCompnayies) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "SuggestedCompnayies{" +
"id=" + getId() +
"}";
}
}
Company
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
@Column(name = "location")
private String location;
@Column(name = "google_map_location")
private String googleMapLocation;
@Column(name = "longitude")
private String longitude;
@Column(name = "latitude")
private String latitude;
@Column(name = "street_1")
private String street1;
@Column(name = "street_2")
private String street2;
@Column(name = "city")
private String city;
@Column(name = "zipcode")
private Long zipcode;
@Column(name = "contact_number")
private Long contactNumber;
@Column(name = "logo")
private String logo;
@Column(name = "image")
private String image;
@Column(name = "is_pharmacy")
private Boolean isPharmacy;
@Column(name = "is_hospital")
private Boolean isHospital;
@Column(name = "is_laboratory")
private Boolean isLaboratory;
@Column(name = "is_distributor")
private Boolean isDistributor;
@Column(name = "is_group_pharmacy")
private Boolean isGroupPharmacy;
@Column(name = "created_by_id")
private Long createdById;
@Column(name = "updated_by_id")
private Long updatedById;
@Column(name = "created_on")
private Instant createdOn;
@Column(name = "updated_on")
private Instant updatedOn;
@Column(name = "is_approved")
private Boolean isApproved;
@Column(name = "is_active")
private Boolean isActive;
@Column(name = "user_id")
private Long userId;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@OneToMany(mappedBy = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<CompanySubscription> subscriptions = new HashSet<>();
@OneToMany(mappedBy = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<DocumentType> types = new HashSet<>();
@OneToMany(mappedBy = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Review> reviews = new HashSet<>();
@OneToMany(mappedBy = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Rating> ratings = new HashSet<>();
@OneToMany(mappedBy = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<WorkingHour> workingHours = new HashSet<>();
@OneToMany(mappedBy = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Gallery> galleries = new HashSet<>();
@OneToMany(mappedBy = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Company> parentCompanies = new HashSet<>();
@OneToMany(mappedBy = "company")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<SuggestedCompnayies> suggestedComapnies = new HashSet<>();
@ManyToOne
@JsonIgnoreProperties("companies")
private State state;
@ManyToOne
@JsonIgnoreProperties("parentCompanies")
private Company company;
@ManyToMany(mappedBy = "companies")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JsonIgnore
private Set<Partner> partners = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public Company name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public Company email(String email) {
this.email = email;
return this;
}
public void setEmail(String email) {
this.email = email;
}
public String getLocation() {
return location;
}
public Company location(String location) {
this.location = location;
return this;
}
public void setLocation(String location) {
this.location = location;
}
public String getGoogleMapLocation() {
return googleMapLocation;
}
public Company googleMapLocation(String googleMapLocation) {
this.googleMapLocation = googleMapLocation;
return this;
}
public void setGoogleMapLocation(String googleMapLocation) {
this.googleMapLocation = googleMapLocation;
}
public String getLongitude() {
return longitude;
}
public Company longitude(String longitude) {
this.longitude = longitude;
return this;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public Company latitude(String latitude) {
this.latitude = latitude;
return this;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getStreet1() {
return street1;
}
public Company street1(String street1) {
this.street1 = street1;
return this;
}
public void setStreet1(String street1) {
this.street1 = street1;
}
public String getStreet2() {
return street2;
}
public Company street2(String street2) {
this.street2 = street2;
return this;
}
public void setStreet2(String street2) {
this.street2 = street2;
}
public String getCity() {
return city;
}
public Company city(String city) {
this.city = city;
return this;
}
public void setCity(String city) {
this.city = city;
}
public Long getZipcode() {
return zipcode;
}
public Company zipcode(Long zipcode) {
this.zipcode = zipcode;
return this;
}
public void setZipcode(Long zipcode) {
this.zipcode = zipcode;
}
public Long getContactNumber() {
return contactNumber;
}
public Company contactNumber(Long contactNumber) {
this.contactNumber = contactNumber;
return this;
}
public void setContactNumber(Long contactNumber) {
this.contactNumber = contactNumber;
}
public String getLogo() {
return logo;
}
public Company logo(String logo) {
this.logo = logo;
return this;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getImage() {
return image;
}
public Company image(String image) {
this.image = image;
return this;
}
public void setImage(String image) {
this.image = image;
}
public Boolean isIsPharmacy() {
return isPharmacy;
}
public Company isPharmacy(Boolean isPharmacy) {
this.isPharmacy = isPharmacy;
return this;
}
public void setIsPharmacy(Boolean isPharmacy) {
this.isPharmacy = isPharmacy;
}
public Boolean isIsHospital() {
return isHospital;
}
public Company isHospital(Boolean isHospital) {
this.isHospital = isHospital;
return this;
}
public void setIsHospital(Boolean isHospital) {
this.isHospital = isHospital;
}
public Boolean isIsLaboratory() {
return isLaboratory;
}
public Company isLaboratory(Boolean isLaboratory) {
this.isLaboratory = isLaboratory;
return this;
}
public void setIsLaboratory(Boolean isLaboratory) {
this.isLaboratory = isLaboratory;
}
public Boolean isIsDistributor() {
return isDistributor;
}
public Company isDistributor(Boolean isDistributor) {
this.isDistributor = isDistributor;
return this;
}
public void setIsDistributor(Boolean isDistributor) {
this.isDistributor = isDistributor;
}
public Boolean isIsGroupPharmacy() {
return isGroupPharmacy;
}
public Company isGroupPharmacy(Boolean isGroupPharmacy) {
this.isGroupPharmacy = isGroupPharmacy;
return this;
}
public void setIsGroupPharmacy(Boolean isGroupPharmacy) {
this.isGroupPharmacy = isGroupPharmacy;
}
public Long getCreatedById() {
return createdById;
}
public Company createdById(Long createdById) {
this.createdById = createdById;
return this;
}
public void setCreatedById(Long createdById) {
this.createdById = createdById;
}
public Long getUpdatedById() {
return updatedById;
}
public Company updatedById(Long updatedById) {
this.updatedById = updatedById;
return this;
}
public void setUpdatedById(Long updatedById) {
this.updatedById = updatedById;
}
public Instant getCreatedOn() {
return createdOn;
}
public Company createdOn(Instant createdOn) {
this.createdOn = createdOn;
return this;
}
public void setCreatedOn(Instant createdOn) {
this.createdOn = createdOn;
}
public Instant getUpdatedOn() {
return updatedOn;
}
public Company updatedOn(Instant updatedOn) {
this.updatedOn = updatedOn;
return this;
}
public void setUpdatedOn(Instant updatedOn) {
this.updatedOn = updatedOn;
}
public Boolean isIsApproved() {
return isApproved;
}
public Company isApproved(Boolean isApproved) {
this.isApproved = isApproved;
return this;
}
public void setIsApproved(Boolean isApproved) {
this.isApproved = isApproved;
}
public Boolean isIsActive() {
return isActive;
}
public Company isActive(Boolean isActive) {
this.isActive = isActive;
return this;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Long getUserId() {
return userId;
}
public Company userId(Long userId) {
this.userId = userId;
return this;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public Company username(String username) {
this.username = username;
return this;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public Company password(String password) {
this.password = password;
return this;
}
public void setPassword(String password) {
this.password = password;
}
public Set<CompanySubscription> getSubscriptions() {
return subscriptions;
}
public Company subscriptions(Set<CompanySubscription> companySubscriptions) {
this.subscriptions = companySubscriptions;
return this;
}
public Company addSubscription(CompanySubscription companySubscription) {
this.subscriptions.add(companySubscription);
companySubscription.setCompany(this);
return this;
}
public Company removeSubscription(CompanySubscription companySubscription) {
this.subscriptions.remove(companySubscription);
companySubscription.setCompany(null);
return this;
}
public void setSubscriptions(Set<CompanySubscription> companySubscriptions) {
this.subscriptions = companySubscriptions;
}
public Set<DocumentType> getTypes() {
return types;
}
public Company types(Set<DocumentType> documentTypes) {
this.types = documentTypes;
return this;
}
public Company addTypes(DocumentType documentType) {
this.types.add(documentType);
documentType.setCompany(this);
return this;
}
public Company removeTypes(DocumentType documentType) {
this.types.remove(documentType);
documentType.setCompany(null);
return this;
}
public void setTypes(Set<DocumentType> documentTypes) {
this.types = documentTypes;
}
public Set<Review> getReviews() {
return reviews;
}
public Company reviews(Set<Review> reviews) {
this.reviews = reviews;
return this;
}
public Company addReviews(Review review) {
this.reviews.add(review);
review.setCompany(this);
return this;
}
public Company removeReviews(Review review) {
this.reviews.remove(review);
review.setCompany(null);
return this;
}
public void setReviews(Set<Review> reviews) {
this.reviews = reviews;
}
public Set<Rating> getRatings() {
return ratings;
}
public Company ratings(Set<Rating> ratings) {
this.ratings = ratings;
return this;
}
public Company addRatings(Rating rating) {
this.ratings.add(rating);
rating.setCompany(this);
return this;
}
public Company removeRatings(Rating rating) {
this.ratings.remove(rating);
rating.setCompany(null);
return this;
}
public void setRatings(Set<Rating> ratings) {
this.ratings = ratings;
}
public Set<WorkingHour> getWorkingHours() {
return workingHours;
}
public Company workingHours(Set<WorkingHour> workingHours) {
this.workingHours = workingHours;
return this;
}
public Company addWorkingHours(WorkingHour workingHour) {
this.workingHours.add(workingHour);
workingHour.setCompany(this);
return this;
}
public Company removeWorkingHours(WorkingHour workingHour) {
this.workingHours.remove(workingHour);
workingHour.setCompany(null);
return this;
}
public void setWorkingHours(Set<WorkingHour> workingHours) {
this.workingHours = workingHours;
}
public Set<Gallery> getGalleries() {
return galleries;
}
public Company galleries(Set<Gallery> galleries) {
this.galleries = galleries;
return this;
}
public Company addGallery(Gallery gallery) {
this.galleries.add(gallery);
gallery.setCompany(this);
return this;
}
public Company removeGallery(Gallery gallery) {
this.galleries.remove(gallery);
gallery.setCompany(null);
return this;
}
public void setGalleries(Set<Gallery> galleries) {
this.galleries = galleries;
}
public Set<Company> getParentCompanies() {
return parentCompanies;
}
public Company parentCompanies(Set<Company> companies) {
this.parentCompanies = companies;
return this;
}
public Company addParentCompany(Company company) {
this.parentCompanies.add(company);
company.setCompany(this);
return this;
}
public Company removeParentCompany(Company company) {
this.parentCompanies.remove(company);
company.setCompany(null);
return this;
}
public void setParentCompanies(Set<Company> companies) {
this.parentCompanies = companies;
}
public Set<SuggestedCompnayies> getSuggestedComapnies() {
return suggestedComapnies;
}
public Company suggestedComapnies(Set<SuggestedCompnayies> suggestedCompnayies) {
this.suggestedComapnies = suggestedCompnayies;
return this;
}
public Company addSuggestedComapnies(SuggestedCompnayies suggestedCompnayies) {
this.suggestedComapnies.add(suggestedCompnayies);
suggestedCompnayies.setCompany(this);
return this;
}
public Company removeSuggestedComapnies(SuggestedCompnayies suggestedCompnayies) {
this.suggestedComapnies.remove(suggestedCompnayies);
suggestedCompnayies.setCompany(null);
return this;
}
public void setSuggestedComapnies(Set<SuggestedCompnayies> suggestedCompnayies) {
this.suggestedComapnies = suggestedCompnayies;
}
public State getState() {
return state;
}
public Company state(State state) {
this.state = state;
return this;
}
public void setState(State state) {
this.state = state;
}
public Company getCompany() {
return company;
}
public Company company(Company company) {
this.company = company;
return this;
}
public void setCompany(Company company) {
this.company = company;
}
public Set<Partner> getPartners() {
return partners;
}
public Company partners(Set<Partner> partners) {
this.partners = partners;
return this;
}
public Company addPartners(Partner partner) {
this.partners.add(partner);
partner.getCompanies().add(this);
return this;
}
public Company removePartners(Partner partner) {
this.partners.remove(partner);
partner.getCompanies().remove(this);
return this;
}
public void setPartners(Set<Partner> partners) {
this.partners = partners;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Company)) {
return false;
}
return id != null && id.equals(((Company) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "Company{" +
"id=" + getId() +
", name='" + getName() + "'" +
", email='" + getEmail() + "'" +
", location='" + getLocation() + "'" +
", googleMapLocation='" + getGoogleMapLocation() + "'" +
", longitude='" + getLongitude() + "'" +
", latitude='" + getLatitude() + "'" +
", street1='" + getStreet1() + "'" +
", street2='" + getStreet2() + "'" +
", city='" + getCity() + "'" +
", zipcode=" + getZipcode() +
", contactNumber=" + getContactNumber() +
", logo='" + getLogo() + "'" +
", image='" + getImage() + "'" +
", isPharmacy='" + isIsPharmacy() + "'" +
", isHospital='" + isIsHospital() + "'" +
", isLaboratory='" + isIsLaboratory() + "'" +
", isDistributor='" + isIsDistributor() + "'" +
", isGroupPharmacy='" + isIsGroupPharmacy() + "'" +
", createdById=" + getCreatedById() +
", updatedById=" + getUpdatedById() +
", createdOn='" + getCreatedOn() + "'" +
", updatedOn='" + getUpdatedOn() + "'" +
", isApproved='" + isIsApproved() + "'" +
", isActive='" + isIsActive() + "'" +
", userId=" + getUserId() +
", username='" + getUsername() + "'" +
", password='" + getPassword() + "'" +
"}";
}
}
答案1
得分: 2
你应该先加入相关的实体,即首先与 Company
连接,然后将其属性作为条件添加。
Join<SuggestedCompanies, Company> company = root.join("company");
predicates.add(builder.equal(company.get("isHospital"), isHospital));
对于实体的属性,假设 partnerId
是属性,你可以这样做:
predicates.add(builder.equal(root.get("partnerId"), partnerId));
英文:
You should Join related entity first means join with Company
first and then add as a condition on its property
Join<SuggestedCompnayies, Company> company = root.join("company");
predicates.add(builder.equal(company.get("isHospital"), isHospital));
And for the entity's property suppose partnerId
is property then you can do this way
predicates.add(builder.equal(root.get("partnerId"), partnerId));
答案2
得分: 0
你可能错过了括号,尝试将其更改为:
predicates.add(builder.equal(root.get("companyId").get("isHospital"), isHospital));
英文:
Probably you have missed the bracket, try changing it to:
predicates.add(builder.equal(root.get("companyId")).get("isHospital"), isHospital));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论