0

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? 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).

Thanks!!!

Denis Tulskiy
  • 19,012
  • 6
  • 50
  • 68
forhas
  • 11,551
  • 21
  • 77
  • 111
  • 1
    What is UserDiet? What have you tried? Note that your mapping is wrong: in a bidirectional association, one side must have a mappedBy attribute, and should not define any JoinColumn. – JB Nizet Oct 07 '12 at 07:17

1 Answers1

0

Got it solved by adding to DailyDiet class:

@ManyToOne
protected Diet userDiet;

And then in my DailyDietDao the following predicate:

Predicate userNameCondition = qb.equal(p.get(DailyDiet_.userDiet).get(UserDiet_.user).get(BaseUser_.userDetails).get(UserDetails_.userName),
        userName);
forhas
  • 11,551
  • 21
  • 77
  • 111