1.开发环境Window
2.开发工具MyEclispe5.x
3.JDK1.5
4.使用hibernate的必须包可以用MyEclipse自带的(我的就是),或者上官网http://www.hibernate.org/载相应包
5.使用jdbc的驱动包,根据自己使用的数据库可以下载相应的jdbc驱动包,本人用mysql-connector-java-5.1.6-bin.jar包
6.如果使用测试用例,可以用MyEclipse自带的junit3.8或4的都可以
7.新建项目,使用工具自动生成的hibernate.cfg.xml配置文件,配置文件主要是一些jdbc连接数据库的配置,及表与实体类的映射,连接池的参数配置
8.hibernate有5个核心接口,分别是Session、SessionFactory、Transaction、Query和Configuration详细信息可以参考:http://baike.baidu.com/view/7291.htm
9.参考下hibernate.cfg.xml及测试类Test.java的示例图
<property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate3?characterEncoding=utf-8</property> <property name="connection.username">root</property> <property name="connection.password">admin</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="myeclipse.connection.profile">mysql</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.use_sql_comments">true</property> <!-- 映射文件 --> <mapping resource="one2many1/Class.hbm.xml" /> <mapping resource="one2many1/Student.hbm.xml" />
public void test() {
Session session = null;
try {
session = HibernateSessionFactory.getSession();
session.beginTransaction();
List students = session.createSQLQuery("select id,name from t_student ").list();
for (Iterator iter=students.iterator(); iter.hasNext();) {
Object[] obj = (Object[])iter.next();
System.out.println(obj[0] + "," + obj[1]);
}
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}finally {
HibernateSessionFactory.closeSession(session);
}
}