[英]Is there a way to return Specifications for Parent Entity for org.springframework.data.jpa.domain.Specification?
Suppose I have a bidirectional 1-1 association with the Person entity 假设我与Person实体具有双向1-1关联
@Entity
public class Person {
@OneToOne(optional=false)
@JoinColumn(name = "contact_id")
private Contact contact;
// getters/setters/constructors
}
And the Contact Entity 和联系实体
@Entity
public class Contact {
@OneToOne(mappedBy="contact")
private Person person;
// getters/setters/
}
I couldn't find a way to select parent object for Person Entity using the Contact entity. 我找不到使用联系人实体为“人物实体”选择父对象的方法。 Like so...
像这样
criteriaQuery.select(root.get(Contact_.person));
I get this error: 我收到此错误:
Incompatible types. 不兼容的类型。 Required Selection<?
必填项<? extends capture of ?> but 'get' was inferred to Path<Y>: no instance(s) of type variable(s) exist so that Person conforms to capture of ?
扩展了对?>的捕获,但将'get'推断为Path <Y>:不存在类型变量的实例,因此Person符合对?
Is there a way of doing this? 有办法吗? I wanted to return a Predicate for Person Entity using the Contact root.
我想使用Contact根返回一个Person实体的谓词。 For eg.
例如。
public static Specification<Person> phoneWithCountryCode(String countryCode) {
return new Specification<Person>() {
@Override
public Predicate toPredicate(
Root<Contact> root,
CriteriaQuery<?> criteriaQuery,
CriteriaBuilder criteriaBuilder
) {
String startsWithPattern = countryCode + "%";
criteriaQuery.select(root.get(Contact_.person));
return criteriaBuilder.like(
root.get(Contact_.phone), startsWithPattern
);
}
};
}
Yes, you can do. 是的,你可以的。 I did it.I Have Relationship ( Book -- Review).
我做到了,我有关系(书-复习)。
In your case create Specification<Person>
and use join with contact. 在您的情况下,创建
Specification<Person>
并与联系人一起使用join。 like this, 像这样,
Join joins = root.join("contact");
If help requires just follow my code. 如果需要帮助,请遵循我的代码。
public class BookSpecification {
public static Specification<Book> getBookByNameAndReviewId(){
return new Specification<Book> () {
@Override
public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder cb)
{
//List<javax.persistence.criteria.Predicate>
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(root.get("name"), "spring boot"));
Join joins = root.join("reviews");
predicates.add(cb.equal(joins.get("no") , 584));
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
// return cb.equal(root, predicates);
}
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.