配置方法和步骤¶
- 打开MyEclipse或者Eclipse,新建一个Java project项目hibernate。右键点击左侧窗口空白处选择New——Java project,如下图:
- 在工程下创建lib文件夹,将所准备完成的jar包复制到lib中,如下图:
- 在src中建立test包,在test包中创建test_model.java,此为表test的映射模型,代码如下:
//create table test(id int,name varchar(10),age int,sex varchar(10));
//insert into test values(1,'testname1',11,'w');insert into test values(2,'testname2',12,'w'); insert into test values(3,'testname3',13,'m');
package test;
public class test_model {
private int id;
private String name;
private int age;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public void shout() {
System.out.println("id: "+id+" name: "+name+" age: "+age+" sex: "+sex);
}
}
- 创建test_hbm.xml,此文件为建立test表和test_model模型之间关系的配置文件,代码如下:
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="test.test_model" table="test">
<id name="id" column="ID" type="int">
<generator class="assigned" />
</id>
<property name="name" column="NAME" type="string" />
<property name="age" type="int" />
<property name="sex" type="string" />
</class>
</hibernate-mapping>
- 创建hibernate.cfg.xml,此文件名不可以更改。代码如下:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--程序执行的时候是否显示真正的sql语句 -->
<property name="show_sql">true</property>
<!--使用的SQL对应的“方言” -->
<property name="dialect">
org.hibernate.dialect.OscarDialect
</property>
<!--连接数据库的Driver -->
<property name="connection.driver_class">
com.oscar.Driver
</property>
<!--数据库连接url -->
<property name="connection.url">
jdbc:oscar://192.168.1.13:2003/OSRDB
</property>
<!--用户名 -->
<property name="connection.username">SYSDBA</property>
<!--密码 -->
<property name="connection.password">szoscar55</property>
<!--加载映射关系-->
<mapping resource="test/test_hbm.xml"/>
</session-factory>
</hibernate-configuration>