Reputation: 5667
I had the following code sample that returns a list of friends from my database use Hibernate and it works get but I know change the function to pass in String which is the user. How can I change the following code to return all friends that username match the String i pass in?
public List<Friend> listFriends()
{
return (List<Friend>) sessionFactory.getCurrentSession()
.createCriteria(Friend.class).list();
}
Upvotes: 2
Views: 3041
Reputation: 586
There's a couple ways to do it. The first and most straight forward is to use a restriction.
public List<Friend> listFriends(String userName) {
return (List<Friend>) sessionFactory.getCurrentSession()
.createCriteria(Friend.class)
.add(Restrictions.eq("userName", userName) )
.list();
}
Another way would be to use an example.
public List<Friend> listFriends(String userName) {
Friend friend = new Friend();
friend.setUserName(userName);
return (List<Friend>) sessionFactory.getCurrentSession()
.createCriteria(Friend.class)
.add(Example.create(friend))
.list();
}
Upvotes: 3