Search code examples
javahibernatedynamichibernate-criteria

How can I get table records passing table name and column names at runtime in hibernate?


Requirement is to get the records from database where particular columns and the table name is selected at run time.

I am using Java, Hibernate and Mysql. It is possible using JDBC. but i want to do it using hibernate.

Post the hints, if anybody knows

Thanks in advance


Solution

  • Well, Hibernate can do much more than just JDBC, what you're looking for can be written like this with Hibernate:

    Query query = session.createSQLQuery(
    "select s.stock_code from stock s where s.stock_code = :stockCode")
    .setParameter("stockCode", "7277");
    List result = query.list();
    

    As you can see the table name and columns can be defined on the fly, this is at least on par with JDBC, and probably even simpler. You don't have to use parameters, you can modularly build your query in the code, obviously.

    Reference for more details https://www.mkyong.com/hibernate/hibernate-native-sql-queries-examples/