这是我的基本功能:
public static void main(String[] a) throws Exception { Session sessione = HibernateUtil.getSessionFactory().openSession(); Query query = sessione.createSQLQuery("select * from User").addEntity(User.class); List<User> 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()); }
此功能能够连接并在我的数据库上执行查询…
我想创建相同的功能,但更通用。…前一个仅用于一个表(User),新表必须能够接受String查询的参数作为输入,以及将在其中执行查询的类类型。这将允许我仅使用一行来执行查询。
User
String
应该是这样的:
public static void queryResult(String query, <ClassOfTable>) { Session sessione = HibernateUtil.getSessionFactory().openSession(); Query qy = sessione.createSQLQuery(query).addEntity(<ClassOfTable>.class); List<<ClassOfTable>> rows = qy.list(); Iterator it = rows.iterator(); while (it.hasNext()) { <ClassOfTable> obj = (<ClassOfTable>) it.next(); } }
您发现ClassOfTable我不知道如何“通用”代码…
ClassOfTable
我希望已经清楚了…
PS ClassOfTable应该是DB(Hibernate)中表的类的代表。
Hibernate
谢谢。
public static <T> 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 } }
如果您打算返回结果集,请使用:
public static <T> List<T> queryResult(String query, Class<? extends T> clazz) { Session session = HibernateUtil.getSessionFactory().openSession(); Query q = session.createSQLQuery(query).addEntity(clazz); List<T> rows = (List<T>) q.list(); return Collections.unmodifiableList(rows); } // now call generic method List<User> 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()); });