Reputation: 7852
I have two Java Hibernate
entities user
and userPick
:
@Entity
@Table(name="users")
public class User{
@Column(length=50)
private String name;
@OneToMany
private List<UserPick> userPicks = new ArrayList<UserPick>(0);
...
and
@Entity
@Table(name="usersPicks")
public class UserPick {
...
User user; // this line no exist in code
// I want get it when load all picks
// I am confused here or I can do it, because in user is
// List<userPick> and it sounds like circle
// user.getUserPicks().getUser().getUserPicks()....
...
When I load user everythings ok.
public User findByUserName(String name) {
Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.eq("name",name));
List<User> users = criteria.list();
if (users.size() > 0) {
return users.get(0);
} else {
return null;
}
}
But I looking way how I can get all usersPick's
in one list and get picks users, something like:
public List<UserPick> getAllPicks(){
Criteria criteria = session.createCriteria(UserPick.class);
List<UserPick> picks = criteria.list();
return picks;
}
I want to print pick user name System.out.print(picks.get(0).getUser().getName())
Upvotes: 2
Views: 3083
Reputation: 19956
It is ok to have an association to User
in the UserPick
. To associate User
and UserPick
by a foreign key fk_user
in the UserPick
, please, add mappedBy = "user"
to User
and make association to User
lazy in the UserPick
. To specify a foreign key column name you need @JoinnColumn(name = "fk_user")
.
@Entity
@Table(name="users")
public class User{
@Column(length=50)
private String name;
@OneToMany(mappedBy = "user")
private List<UserPick> userPicks = new ArrayList<UserPick>();
}
@Entity
@Table(name="usersPicks")
public class UserPick {
@ManyToOne(fetch = FetchType.LAZY)
@JoinnColumn(name = "fk_user")
private User user;
}
And you can fetch users by the way suggested by @StanislavL (except that you don't need to make an alias to user
)
public List<UserPick> getAllPicks(){
Criteria criteria = session.createCriteria(UserPick.class)
.setFetchMode("user", FetchMode.JOIN);
return criteria.list();
}
Even if an association to User
in UserPick
is not lazy It is not a problem because of Hibernate uses a cache to set the same User
to all user's UserPick
.
Upvotes: 3
Reputation: 57381
criteria.setFetchMode("user", FetchMode.JOIN)
.createAlias("user", "user")
The FetchMode.JOIN should solve n+1 query problem
Upvotes: 1