2

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?

1
  • yes it is possible , write the query you want to run , in order to help you Commented Nov 10, 2015 at 6:13

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0
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)

Comments

0

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.

i.e. List < User > users = (List < User > )getHibernateTemplate("from User");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.