This is my basic function:
public static void main(String[] a) throws Exception {
Session sessione = HibernateUtil.getSessionFactory().openSession();
Query query = sessione.createSQLQuery("select * from User").addEntity(User.class);
List rows = query.list();
Iterator it = rows.iterator();
while (it.hasNext()) {
User usr = (User) it.next();
System.out.println(usr.getEmail());
System.out.println(usr.getName());
System.out.println(usr.getIdUser());
System.out.println(usr.getUser());
}
This function is capable to connect and perform a query on my DB...
I want to create the same function but more general... The previous was specific for only one table (User), the new one must be able to accept as input a String parameter for the query, and the class type where the query will be executed. This will allow me to use only one row in order to perform a query.
It should be something like this:
public static void queryResult(String query, ) {
Session sessione = HibernateUtil.getSessionFactory().openSession();
Query qy = sessione.createSQLQuery(query).addEntity(.class);
List<> rows = qy.list();
Iterator it = rows.iterator();
while (it.hasNext()) {
obj = () it.next();
}
}
Where you find ClassOfTable I don't know how to "generalize" the code...
I hope to have been clear...
P.S. ClassOfTable should be the class rappresentative of a table in DB (Hibernate).
Thanks.
解决方案
public static void queryResult(String query, Class extends T> clazz) {
Session session = HibernateUtil.getSessionFactory().openSession();
Query q = session.createSQLQuery(query).addEntity(clazz);
List rows = q.list();
Iterator it = rows.iterator();
while (it.hasNext()) {
T t = (T) it.next();
// do your work on object t
}
}
If your intention is to return resultset, use:
public static List queryResult(String query, Class extends T> clazz) {
Session session = HibernateUtil.getSessionFactory().openSession();
Query q = session.createSQLQuery(query).addEntity(clazz);
List rows = (List) q.list();
return Collections.unmodifiableList(rows);
}
// now call generic method
List users = queryResult("select * from User", User.class);
users.forEach(usr -> {
System.out.println(usr.getEmail());
System.out.println(usr.getName());
System.out.println(usr.getIdUser());
System.out.println(usr.getUser());
});