tags:

views:

165

answers:

1

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";
+3  A: 

It is possible to get this information as shown below, but I am not sure that I would do this in production code unless I really need the table names to be changeable after the code has been compiled. Otherwise, is it really worth the readability cost to your code to have this?

AbstractEntityPersister metadata = 
    (AbstractEntityPersister) sessionFactory.getClassMetadata(User.class);
String tableName = metadata.getTableName();
String[] columnNames = metadata.getKeyColumnNames();
Tendayi Mawushe
One could of course encapsulate this verbose API in a utility method, but yes, some clutter will remain.
meriton
@meriton agreed you could wrap this in a utility method, I just wanted serg555 to question whether this sort of cleverness is necessary. Wanted to put a thumb on the scale on the side of simplicity.
Tendayi Mawushe