Retrieving all rows of a table without HQL?

Hibernate

Hibernate Problem Overview


I am using Hibernate 4 and would like to simply list all rows of a table. All solutions I found suggest using something like "from tablename", but I would like to avoid hardcoding tablenames in strings.

Hibernate Solutions


Solution 1 - Hibernate

You can use

session.createCriteria(MyEntity.class).list();

for example.

Solution 2 - Hibernate

HQL doesn't use table names. It uses entity names. And entity names are (by default) class names. So you can use

String hql = "select a from " + TheEntity.class.getSimpleName() + " a";

But I would favor readability over type safety here, and use

String hql = "select a from TheEntity a";

You should have automated tests for your queries anyway.

Solution 3 - Hibernate

//Hibernate Class

public class CommonDAO<T> {

 Session session = null;
 Transaction transaction = null;
 private Class<T> clazz;

 public CommonDAO(){ //constructor
    session = HibernateUtil.getSessionFactory().openSession();
    transaction = session.beginTransaction();
    Type genericSuperclass = this.getClass().getGenericSuperclass();
    if (genericSuperclass instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) genericSuperclass;
      Type type = pt.getActualTypeArguments()[0];
      clazz = (Class<T>) type;
    }
 }

 public T listById(Object id) {
  T object = null;
  try {
   object = (T) session.get(clazz, (Serializable) id);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return object;
 }
}

//User Class

public class UserDAO extends CommonDAO<UserMaster> { // Here UserMaster is pojo
 
 public UserDAO() {
  super();
 }

 public static void main(String ar[]) {
  UserMaster user = new UserDAO().listById(1); // 1 is id
  System.out.println(user.getUserName());
 }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcus RiemerView Question on Stackoverflow
Solution 1 - HibernatemrabView Answer on Stackoverflow
Solution 2 - HibernateJB NizetView Answer on Stackoverflow
Solution 3 - HibernateManishView Answer on Stackoverflow