初学hibernate ,花了点时间写了个一对一关系的两个表,遇到了无法显示查询内容的小问题,四处找文档没找到,现已经解决,结果如下:
调用程序如下:
import java.util.Iterator;
public class Client {
public Client() {
}
public static void main(String[] args){
BlogMain blogMain=new BlogMain();
try{
blogMain.exportTables();
blogMain.configure();
Blog blog = blogMain.createBlog("test");
blogMain.createBlogItem(blog,"test1","string1");
blogMain.createBlogItem(blog,"test2","string2");
blogMain.createBlogItem(blog,"test3","string3");
List list=blogMain.listBlogsAndRecentItems();
Iterator it=list.iterator();
while (it.hasNext()){
Object[] Row = (Object[])it.next();
Blog blogtest=(Blog)Row[0];
BlogItem blogItem=(BlogItem)Row[1];
System.out.println(blogtest.getId()+":"+blogItem.getId()+":"+blogItem.getText());
}
}
catch(HibernateException ex){
throw new RuntimeException("Exception building SessionFactory: " + ex.getMessage(), ex);
}
}
}
其中 blogMain.listBlogsAndRecentItems();代码如下
public List listBlogsAndRecentItems() throws HibernateException {
Session session = _sessions.openSession();
Transaction tx = null;
List result = null;
try {
tx = session.beginTransaction();
Query q = session.createQuery(
"from Blog as blog " +
"inner join blog.items as blogItem " +
"where blogItem.datetime > :minDate"
);
Calendar cal = Calendar.getInstance();
cal.roll(Calendar.MONTH, false);
q.setCalendar("minDate", cal);
result = q.list();
tx.commit();
}
catch (HibernateException he) {
if (tx!=null) tx.rollback();
throw he;
}
finally {
session.close();
}
return result;
}
查询显示结果如下:
1:2:string1
1:3:string2
1:4:string3
本文地址:http://com.8s8s.com/it/it14063.htm