使用 Criteria select 数据库中的特定字段?
Use Criteria to select a particular field from DB?
我有如下方法
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()
}
这将 return 我从数据库中获取整个资源,但我需要的只是资源的名称。我怎样才能做到这一点?
使用Projection
,您可以在Hibernate documentation中找到示例。
Criteria criteria = session.createCriteria(Resource.class);
criteria.setProjection(Property.forName("name"))
criteria.add(Restrictions.like("name", searchString));
通过使用Projection
you will get other fields (Which you did not got by Projection) in your Pojo
setted to default values. In HQL
,您可以获得指定的列值,如下所示:
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]);
}
希望对您有所帮助。
我有如下方法
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()
}
这将 return 我从数据库中获取整个资源,但我需要的只是资源的名称。我怎样才能做到这一点?
使用Projection
,您可以在Hibernate documentation中找到示例。
Criteria criteria = session.createCriteria(Resource.class);
criteria.setProjection(Property.forName("name"))
criteria.add(Restrictions.like("name", searchString));
通过使用Projection
you will get other fields (Which you did not got by Projection) in your Pojo
setted to default values. In HQL
,您可以获得指定的列值,如下所示:
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]);
}
希望对您有所帮助。