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

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

For example, instead of:

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

sort of:

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

You can get this information, as shown below, but I'm not sure that I will do this in production code if I really do not need the names of the tables that can be changed after compiling the code. Otherwise, is it really worth the read value for your code?

AbstractEntityPersister metadata = 
    (AbstractEntityPersister) sessionFactory.getClassMetadata(User.class);
String tableName = metadata.getTableName();
String[] columnNames = metadata.getKeyColumnNames();
+4
source

Source: https://habr.com/ru/post/1741846/


All Articles