4

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";

1 Answer 1

5

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

2 Comments

One could of course encapsulate this verbose API in a utility method, but yes, some clutter will remain.
@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.

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.