我需要创建自定义Hibernate查询。
REM Opening folder with a file selected
START /W EXPLORER /SELECT,\\10.10.10.10\C$\ThisFolder\FileToHighlight.txt
REM Unreliably waiting for window to open
TIMEOUT /T 3 /NOBREAK >NUL
REM Taking screenshot of window with a third-party app
START .\Bin\screenshot-cmd.exe -wt "ThisFolder" -o .\Screenshots\%var%.png
我需要添加限制附加条件。我有其他模型 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
。
我需要找到有照片的用户。
user_id
模型包含:
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;
}
但它不起作用。
问题不在于如何组合2个限制,如何添加限制的问题是NoNotNull ...用户对照片一无所知。照片了解用户,因为他们有user_id。
UPDATED2 :
restrictions.add(builder.isNotNull(user.get("photos")));
SQL:
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)
答案 0 :(得分:0)
试试这个:
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;
在这个中,您可以双向映射,以便您可以从照片中访问用户和用户的照片。
答案 1 :(得分:0)
我自己找到了解决方案。完整代码:
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();