Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate's Transformers.aliasToBean() method

Tags:

java

hibernate

 Query query =  getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(
                 "select proj_employee.employee_no as employeeNo, ...
 .setResultTransformer(Transformers.aliasToBean(User.class));

Inside User.class does the property employeNo need to be in capital letter?

private String EMPLOYEENO; 
//get/set for EMPLOYEENO


If I change the EMPLOYEENO to small letter, it doesn't work. Can anyone explain why the variable name must be all capital letters?

like image 769
cometta Avatar asked Mar 15 '10 04:03

cometta


2 Answers

See the Hibernate 3.2: Transformers for HQL and SQL blog post:

SQL Transformers

With native sql returning non-entity beans or Map's is often more useful instead of basic Object[]. With result transformers that is now possible.

List resultWithAliasedBean = s.createSQLQuery(
  "SELECT st.name as studentName, co.description as courseDescription " +
  "FROM Enrolment e " +
  "INNER JOIN Student st on e.studentId=st.studentId " +
  "INNER JOIN Course co on e.courseCode=co.courseCode")
  .addScalar("studentName")
  .addScalar("courseDescription")
  .setResultTransformer( Transformers.aliasToBean(StudentDTO.class))
  .list();

StudentDTO dto =(StudentDTO) resultWithAliasedBean.get(0);

Tip: the addScalar() calls were required on HSQLDB to make it match a property name since it returns column names in all uppercase (e.g. "STUDENTNAME"). This could also be solved with a custom transformer that search the property names instead of using exact match - maybe we should provide a fuzzyAliasToBean() method ;)

Maybe you are facing the same situation than the one described in the tip in which case you should try to add calls to addScalar().

like image 134
Pascal Thivent Avatar answered Nov 07 '22 09:11

Pascal Thivent


Consider putting column aliases in double quotes. Oracle doesn't uppercase aliases specified in double quotes.

Query query =  getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(
                 "select proj_employee.employee_no \"employeeNo\", ...
 .setResultTransformer(Transformers.aliasToBean(User.class))

;

like image 42
Misha Avatar answered Nov 07 '22 08:11

Misha