How to write native SQL queries in Hibernate without hardcoding table names and fields?

Posted by serg555 on Stack Overflow See other posts from Stack Overflow or by serg555
Published on 2010-04-19T22:02:37Z Indexed on 2010/04/19 22:13 UTC
Read the original article Hit count: 127

Filed under:
|

Sometimes you have to write some of your queries in native SQL rather than hibernate HQL. Is there a nice way to avoid hardcoding table names and fields and get this data from existing mapping?

For example instead of:

String sql = "select user_name from tbl_user where user_id = :id";

something like:

String sql = "select " + Hibernate.getFieldName("user.name") + " from " + Hibernate.getTableName(User.class) + " where " + Hibernate.getFieldName("user.id") + " = :id";

© Stack Overflow or respective owner

Related posts about hibernate

Related posts about java