SJS
SJS

Reputation: 5667

How do return a list with Hibernate search on one col?

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

Answers (1)

JonMR
JonMR

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

Related Questions