最近整理了一下以前做的hibernate的例子.想和大家进行交流. 在hibernate中,one-to-many的例子最典型的是"学生和书"之间的关系,一个学生可以有很多本书,但是每一本书只能属于一个学生,这个简单的例子在hibernate中就称做为一对多的映射关系. 开发hibernate最好的工具我认为要算eclipse了,结合myeclipse插件,可以很好的开发的hibernate.(如果你要开发jsp,可以装lomboz插件,它很好的支持jsp开发,当然不装这个插件也是可以在eclipse下开发jsp的.还有一个emf插件支持j2ee开发,也特别的好!)
首先建立一张表,sql 语句如下: create database bs
create table student (sid varchar(32) not null primary key, sname varchar(16), sage varchar(16), )
create table book (bid varchar(32) not null primary key, bname varchar(16), bprice varchar(16), sid varchar(32) ) 现在表建好了,在eclipse中进行hibernate映射,生成配置文件(本例中是Book.hbm.xml 和Student.hbm.xml文件), 配置文件如下: //Book.hbm.xml
"-//Hibernate/Hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
//Student.hbm.xml
"-//Hibernate/Hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
然后写两个Bean类,代码如下: //Student.java
/* * Created on 2005-3-28 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package eg; import java.util.Set; /** * @author Administrator * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class Student { private String sid; private String sname; private String sage; private Set book; public Student() { //must be imply; } public String getSid() { return sid; } public void setSid(String sid) { this.sid=sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname=sname; } public String getSage() { return this.sage; } public void setSage(String sage) { this.sage=sage; } public Set getBook() { return this.book; } public void setBook(Set book) { this.book=book; } } //Book.java
/* * Created Mon Mar 28 16:55:19 CST 2005 by MyEclipse Hibernate Tool. */ package eg;
//import java.io.Serializable;
/** * A class that represents a row in the 'book' table. * This class may be customized as it is never re-generated * after being created. */ public class Book //extends AbstractBook //implements Serializable { private String bid; private String bname; private String bprice;
/** * Simple constructor of Book instances. */ public Book() { }
/** * Constructor of Book instances given a simple primary key. * @param bid */ // public Book(java.lang.String bid) // { // super(bid); // }
/* Add customized code below */ public void setBid(String bid) { this.bid=bid; } public String getBid() { return this.bid; } public void setBname(String bname) { this.bname=bname; } public String getBname() { return this.bname; } public void setBprice(String bprice) { this.bprice=bprice; } public String getBprice() { return this.bprice; } }
现在可以写一个测试类来测试hibernate中一对多的Demo了, /* * Created on 2005-3-28 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package eg; //import java.sql.SQLException; import java.util.*;
//import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.*;
/** * @author Administrator * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class TestOnetoMany { private SessionFactory sf; private Session session; public TestOnetoMany() { } public void doInsert() { try { session =HibernateSessionFactory.currentSession();
Student student=new Student(); student.setSname("小李"); student.setSage("22"); Set bookset =new HashSet(); Book book=null; for(int i=0;i<2;i++) { book =new Book(); book.setBname("JAVA"+Integer.toString(i)); book.setBprice("50"); bookset.add(book); //System.out.print("测试........添加数据成功!");
} student.setBook(bookset); session.save(student); session.flush(); session.connection().commit(); } catch (Exception ex){ ex.printStackTrace(); } finally { try { session.close(); } catch(HibernateException hex2) { hex2.printStackTrace(); } } System.out.print("插入操作已经结束!............................"); } //插入操作已经结束......................................... //开始查询操作............................................. public void doQuery() { try { session=HibernateSessionFactory.currentSession(); Query query=session.createQuery("from Student as s "); List list=query.list(); Student s=null; //Book book=null; for(int j=0;j{ s=(Student)list.get(j); System.out.println("姓名:"+s.getSname()); System.out.println("年龄:"+s.getSage()); System.out.println("所有的书:"); //测试从student中取出的数据 Iterator iterator = s.getBook().iterator(); while(iterator.hasNext()) { Book book=(Book)iterator.next(); System.out.println("书名:"+book.getBname()); System.out.println("书的价格:"+book.getBprice()); } // System.out.println("it's ok!"); }
} catch(HibernateException hex) { hex.printStackTrace();
} catch(Exception ex) { ex.printStackTrace(); } /*catch(SQLException ex) { ex.printStackTrace(); }*/ finally { try { session.close(); } catch(HibernateException hex3) { hex3.printStackTrace(); } } } public static void main(String [] a) throws HibernateException { TestOnetoMany test=new TestOnetoMany(); test.doInsert(); test.doQuery(); }
}
注意:session是由sessionFactory创建的,sessionFactory 是线程安全的,但是session不是线程安全的,所以在结束的时候要关闭session.
结束语: 利用myeclipse可以很好的开发hibernate,可以通过数据库表进行hibernate映射,自动生成配置文件(*.hbm.xml)和Bean文件,只需要做适当的修改就可以了.此外,还要在工程中加入hibernate的属性文件(log4j.properties和hibernate.properties),这两个属性文件都是对hibernate工程进行必要的初始化工作,如配置连接数据库方言(dialect)等等,必须和hibernate.cfg.xml配置文件在同一目录下,要不然会出现如下警告信息: log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.
|