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.
Asked
Active
Viewed 6.9k times
3 Answers
136
You can use
session.createCriteria(MyEntity.class).list();
for example.

mrab
- 2,702
- 1
- 17
- 10
-
2How could I sort this? – Matthew Moisen Oct 19 '13 at 00:05
-
16session.createCriteria(MyEntity.class).addOrder(Order.asc("age")).list(); – slonik Jan 10 '14 at 13:00
-
5Is there any way to make this type safe? – Sep 08 '15 at 19:05
-
7The method createCriteria(Class) from the type SharedSessionContract is deprecated. – Maske Sep 23 '16 at 20:08
-
@Maske Do you know what to use now? – jamesmstone Sep 08 '17 at 09:34
8
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.

JB Nizet
- 678,734
- 91
- 1,224
- 1,255
-
Yes, queries are tested, but your second solution would still mean that the query wouldn't be taken into account by refactoring. – Marcus Riemer Jan 31 '12 at 17:45
-
1
-
1I agree that in the end its important to get correct results, but as the project is currently in early stages some kind of refactoring happens every week. So properly supporting this is quite vital at the moment. – Marcus Riemer Jan 31 '12 at 17:59
-
-2
//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());
}
}

Manish
- 25
- 1
- 6
-
4
-
2
-
1It is so because your session stays open. What you want to do is *open*, *query*, *close* otherwise you will run into problems with scale. – Louis May 07 '17 at 14:16