简体   繁体   English

使用JPA条件API查询

[英]Query with JPA criteria API

Tried building this query but I guess I'm missing something. 试图建立此查询,但我想我丢失了一些东西。 Here are the involved classes: 以下是涉及的类:

  1. User 用户
  2. Diet 饮食
  3. DailyDiet 日常饮食

Here are the relevant parts of my entities (A pretty simple one): 这是我实体的相关部分(一个非常简单的部分):

public class User {

@Column(name = "User_Name", nullable = false, length = 15, unique = true)
public String userName;

@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, optional = true)
@PrimaryKeyJoinColumn
public Diet userDiet;

}

public class Diet {

@OneToOne(optional = false)
@JoinColumn(name = "User_Id")
protected User user;

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinTable(name = "UsersDiets_DailyDiets", joinColumns = @JoinColumn(name = "User_Id"), inverseJoinColumns = @JoinColumn(name = "DailyDiet_Id"))
protected Collection<DailyDiet> userDailyDiets;
}

public class DailyDiet {

    @Column(name = "Day")
    protected long day;
}

I would like to simply pull a user daily diet of a specific user in a specific day: 我只想简单地介绍特定日期的特定用户的每日饮食:

public UserDiet findByUserNameAndDay(String userName, long day)

But can't seem to make it work. 但是似乎无法使其正常工作。 Should I build 2 different CriteriaQuery objects for that? 我应该为此建立2个不同的CriteriaQuery对象吗? If I create 2 different Predicates, how do I use those? 如果创建两个不同的谓词,该如何使用? If someone can help me with this simple query ill be thankful (I'm quite new to JPA criteria API). 如果有人可以通过这个简单的查询帮助我,请多谢(我对JPA标准API还是很陌生)。

Thanks!!! 谢谢!!!

Got it solved by adding to DailyDiet class: 通过添加到DailyDiet类中来解决它:

@ManyToOne
protected Diet userDiet;

And then in my DailyDietDao the following predicate: 然后在我的DailyDietDao中,以下谓词:

Predicate userNameCondition = qb.equal(p.get(DailyDiet_.userDiet).get(UserDiet_.user).get(BaseUser_.userDetails).get(UserDetails_.userName),
        userName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM