So now I want to return all the rows of a mapped table in Hibernate. Here is the trick: you make a hibernated query using the name of the class mapped to a table, not the actual name of the table in MySQL.
Session sesh3 = NewHibernateUtil.getSessionFactory().getCurrentSession();
sesh3.beginTransaction();
// Interesting thing here: this my select from the mapped class NOT the actual DB table name.
Query qry = sesh3.createQuery("FROM MyMessages");
List l = qry.list();
Iterator i1 = l.iterator();
MyMessages msgs = null;
out.println("Here are all of the rows from the DB:<br />");
while(i1.hasNext()) {
// again, look @ that, we typecast the result of the iterator.
msgs = (MyMessages)i1.next();
out.println("Last Message Time: " + msgs.getStamp());
long id_msg = msgs.getMessageID();
//String.valueOf(id_msg);
out.println("Last Message ID: " + String.valueOf(id_msg));
out.print("<br />");
}
I know I was wondering, when looking over the examples, so here are the import statements:
<%@page import="java.util.Iterator"%>
<%@page import="org.hibernate.Query"%>
<%@page import="java.util.List"%>
<%@page import="hibernatemapping.NewHibernateUtil"%>
<%@page import="org.hibernate.hql.ast.util.SessionFactoryHelper"%>
<%@page import="org.hibernate.Session"%>
<%@page import="hibernatemapping.HiberUtil"%>
<%@page import="org.hibernate.Transaction"%>
<%@page import="java.util.Date"%>
<%@page import="dbclasses.MyMessages"%>
All said and done you get something spit out that looks like this:
Date:Wed Jun 06 13:13:46 EDT 2012 Here is a row from the db Message: Derp derpTime:2012-06-06 04:07:50.0
Here are all of the rows from the DB:
Last Message Time: 2012-06-06 04:07:50.0 Last Message ID: 1
Last Message Time: 2012-06-06 04:34:29.0 Last Message ID: 2
Last Message Time: 2012-06-06 04:35:15.0 Last Message ID: 3
Last Message Time: 2012-06-06 04:36:51.0 Last Message ID: 4
Last Message Time: 2012-06-06 04:37:09.0 Last Message ID: 5
No comments:
Post a Comment