When a class annotated with @Entity
annotaion hibernate uses queries like SELECT * FROM class_name
. But for some reason it is needed to run custom select query for class. Is there a way to provide such query?
Yes, according to the official hibernate reference , you can do it like:
sess.createSQLQuery("SELECT * FROM CATS").addEntity(Cat.class);
or:
sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE FROM CATS").addEntity(Cat.class);
Criteria cr = getCurrentSession().createCritiera(class_name.class)
.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id")
.add(Projections.property("name"), "name"))
.setResultTransformer(Transformers.aliasToBean(class_name.class));
List<class_name> list = cr.list();
Act as select id,name from class_name
this will return List
of class_name
containing objects only have id
and name
and the rest of variables in class_name
will be null
(as you only selected id
and name
)
I would recommend you getHibernatTemplate() from HibernateDaoSupport. Afterwards you can call find("from Class where....") and you get back an object which you can cast to your java class easily.
ie List < User > users = (List < User > )getHibernateTemplate("from User");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.