robin
robin

Reputation: 1925

Use Criteria to select a particular field from DB?

I have a method like below

public List<String> getSimilarResourceNames(String resourceName){
    String searchString = "%"+resourceName+"%";
    Session session = getSession();
    Criteria criteria = session.createCriteria(Resource.class);
    criteria.add(Restrictions.like("name", searchString));
    return  criteria.list()
}

This will return me the entire resource from the DB, but what i need is just the name of the resource. How can I accomplish that ?

Upvotes: 0

Views: 105

Answers (2)

Afsun Khammadli
Afsun Khammadli

Reputation: 2068

By using Projection you will get other fields (Which you did not got by Projection) in your Pojo setted to default values. In HQL you can get specified column values as follow:

Query query = session.createQuery("select u.fullname from Users u");
List<Object[]> rows = query.list();
List<String> fullnames = new ArrayList<String>();
for (Object[] row: rows) {
    fullnames.add(row[0]);
}

I hope this will help you.

Upvotes: 2

Predrag Maric
Predrag Maric

Reputation: 24433

Use Projection, you can find examples in Hibernate documentation.

Criteria criteria = session.createCriteria(Resource.class);
criteria.setProjection(Property.forName("name"))
criteria.add(Restrictions.like("name", searchString));

Upvotes: 3

Related Questions