Retrieving all rows of a table without HQL?

前端 未结 3 1740
栀梦
栀梦 2021-01-31 13:51

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 hardco

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 14:36

    //Hibernate Class

    public class CommonDAO {
    
     Session session = null;
     Transaction transaction = null;
     private Class 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) 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 { // 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());
     }
    }
    

提交回复
热议问题