![](/img/trans.png)
[英]Possible to perform a NOT IN for one-to-many relationship with Hibernate criteria?
[英]Custom hibernate criteria (one-to-many relationship)
我需要創建自定義的Hibernate查詢。
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<User> criteria = builder.createQuery(User.class);
Root<User> user = criteria.from(User.class);
List<Predicate> restrictions = new ArrayList<>();
restrictions.add(builder.equal(user.get("firstname"), user.getFirstName()));
List<User> users = (List<User>) entityManager.createQuery(criteria).getResultList();
我需要添加其他限制條件。 我還有其他模型Photo
,該模型通過外鍵user_id
連接到模型User
。 我需要找到有照片的用戶。
User
模型包含:
private List<Photo> photos;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "photo", cascade = CascadeType.ALL)
@Fetch (FetchMode.SELECT)
@JsonIgnore
public List<Photo> getPhotos() {
return photos;
}
照片模型包含:
private User user;
@ManyToOne
@JoinColumn(name="user_id")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
更新
我需要這樣的東西:
restrictions.add(builder.isNotNull(user.get("photos")));
但它不起作用。
問題不在於如何組合2個限制,問題不在於如何添加限制isNotNull ...用戶對照片一無所知。 照片具有user_id,因此了解用戶。
UPDATED2 :
org.postgresql.util.PSQLException: ERROR: syntax error at or near "."
SQL:
select * from User user0_ cross join Photo photos1_ where user0_.id=photos1_.user and (. is not null)
我需要遵循SQL:
SELECT DISTINCT user.* FROM user
LEFT JOIN photo
ON user.id = photo.user_id;
嘗試這個:
restrictions.add(Restrictions.and(Restrictions.eq(user.get("firstname"), user.getFirstName()),Restrictions.isNotNull(user.get("photos")));
更新:您正在尋找的雙向關系是這樣的:
照片類:
@ManyToOne
@JoinColumn(name="user")
private User user;
用戶類別:
@OneToMany(mappedBy="user")
private Set<Photo> photos;
在這一步中,您將這兩種方式都映射了起來,以便可以訪問用戶中的照片以及用戶中的照片。
我自己找到了解決方案。 完整代碼:
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<User> criteria = builder.createQuery(User.class);
Root<User> user = criteria.from(User.class);
Root<Photo> photo = criteria.from(Photo.class);
List<Predicate> restrictions = new ArrayList<>();
restrictions.add(builder.equal(user.get("firstname"), user.getFirstName()));
restrictions.add(builder.equal(user.get("id"), photo.get("user")));
List<User> users = (List<User>) entityManager.createQuery(criteria).getResultList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.