i have this query with NamedQuery
using Hibernate
this is my sample code.
NamedQuery
@NamedQuery(name="com.company.generic.model.Student.getByID()",query="select name from com.company.generic.model.Student where id=:id")
Java Code
private Student getStudentNameById(Integer id)
{
final Session session = ....
final Query query = session.getNamedQuery("com.company.generic.model.Student.getByID()")
.setParameter("id",id)
.setResultTransformer(Transformers.aliasToBean(Student.class));
final Student student = (Student)query.uniqueResult();
return student;
}
when the query returns all the columns the resultTransformer
works OK but when i return only a few columns returns
Exception in thread "main" org.hibernate.PropertyNotFoundException: Could not find setter for 0 on class com.company.generic.model.Student
my questions are
1). why works with all columns but not working with a few or only a column.
2). which is the diff between namedQuery and Criteria using resultTransformer should namedQuery have setProjection?
3). must i write my own transformer? any workaround...?
thanks a lot...
question #1:
Most probably you need to add alias to name
field in select list
select s.name as name from com.company.generic.model.Student s where s.id=:id
so Hibernate can find the setName(String) method in Student.class
.
Using criteria the equivalent is
session.createCriteria(Student.class)
.add(Restrictions.eq("id",id))
.setProjection(Projections.property("name").as("name"))
.setResultTransformer(Transformers.aliasToBean(Student.class));
question #2:
Named query select list is the projection.
question #3:
see answers above