簡體   English   中英

有沒有一種方法可以返回org.springframework.data.jpa.domain.Specification的父實體規范?

[英]Is there a way to return Specifications for Parent Entity for org.springframework.data.jpa.domain.Specification?

假設我與Person實體具有雙向1-1關聯

@Entity
public class Person {
  @OneToOne(optional=false)
  @JoinColumn(name = "contact_id")
  private Contact contact;


  // getters/setters/constructors
}

和聯系實體

@Entity
public class Contact {
  @OneToOne(mappedBy="contact")
  private Person person;

  // getters/setters/
}

我找不到使用聯系人實體為“人物實體”選擇父對象的方法。 像這樣

criteriaQuery.select(root.get(Contact_.person));

我收到此錯誤:

不兼容的類型。 必填項<? 擴展了對?>的捕獲,但將'get'推斷為Path <Y>:不存在類型變量的實例,因此Person符合對?

有辦法嗎? 我想使用Contact根返回一個Person實體的謂詞。 例如。

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

是的,你可以的。 我做到了,我有關系(書-復習)。

在您的情況下,創建Specification<Person>並與聯系人一起使用join。 像這樣,

Join joins = root.join("contact");

如果需要幫助,請遵循我的代碼。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM