Hibernate作为一个轻量级的框架,其搭建也不是十分的繁琐。以Eclipse为例,手工搭建一个Hibernate工程。
(1)Eclipse中新建一个web工程,将Hibernate的核心jar包加入到WEB-INF下的lib文件夹中。
(2)将数据库的驱动程序包加入到WEB-INF下,比如Oracle的驱动程序jar包ojdbc14。
(3)新建一个hibernate.cfg.xml文件置于src目录下。此文件可以从hibernate 的demo中拷贝一份做相应的内容修改。
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="myeclipse.connection.profile">Oracle 10g</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <property name="connection.username">wu</property> <property name="connection.password">wu</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="show_sql">true</property> <mapping resource="**.hbm.xml" /> </session-factory> </hibernate-configuration>
(4)下面以person表为例,测试一下hibernate环境搭建是否成功
I, 数据库中新建表person
create table person(
id varchar2(32) primary key,
name varchar2(20) not null
)
II,在工程中的src下新建一个demo包,在demo包中新建person的pojo类
public class Person {
private String id = "";
private String name = "";
}
生成相应的getter和setter方法
III,新建Person.hbm.xml文件置于person类的相同目录下。
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="demo">
<class name="Person" table="PERSON">
<id name="id" column="ID" type="string">
<generator class="uuid.hex"/>
</id>
<property name="name" column="NAME" type="string" not-null="true" />
</hibernate-mapping>
IV, 将hibernate.cfg.xml文件做相应的配置,使其能找到Person.hbm.xml文件
<mapping resource="demo/Person.hbm.xml" />
V,测试
demo包下新建一个PersonOperate.java
public class PersonOperate {
private Session session = null;
//构造方法,初始化session对象
public PersonOperate(){
Configuration config = new Configuration().configure();
SessionFactory factory = config.buildSessionFactory();
this.session = factory.openSession();
}
//插入对象
public void savePerson(Person person){
Transaction transaction = this.session.beginTransaction();
this.session.save(person);
transaction.commit();
}
//测试主方法
public static void main(String [] args){
PersonOperate personOperate = new PersonOperate();
/**测试插入数据*/
Person person = new Person();
person.setName("鲁尼");
personOperate.savePerson(person);
}
运行这个java文件,如果数据表person中插入了一条数据,说明配置成功。