- Hibernate真正实现了面向对象的编程,以前我们做项目的时候都是要在数据库中建各种各样的表比较繁琐,Hibernate可以帮助我们通过代码实现表的创建。下面描述一下关于这个过程的详细信息。附注:用到的数据库是Qracle9i。
- 首先是先在你的项目根目录下创建一个配置文件hibernate.cfg.xml,代码如下:
- <?xml version="1.0" encoding="GBK"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory> - //所用到的方言dialect,可以从hibernate3.jar下的jar包中找
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property> - //数据库Qracle9i的驱动类
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> - //连接数据库Qracle9i的url
<property name="hibernate.connection.url">jdbc:oracle:thin:@aserver:1521:erpdbsid</property> - //用户名
<property name="hibernate.connection.username">hibernate</property> - //密码
<property name="hibernate.connection.password">hibernate</property> - //映射资源,com/su02/teacheapp/hibernate/po/Student.hbm.xml,是配置文件Student.hbm.xml的位置,一会再讲如何配置映射文件Student.hbm.xml
<mapping resource="com/su02/teacheapp/hibernate/po/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration> - 第二步:写一个类似于javaBean的类,一定要实现接口Serializable,下面以Student.java为例,代码如下:
- package com.su02.teacheapp.hibernate.po;
- import java.io.Serializable;
- public class Student implements Serializable {
private String id;
private String sname;
private String sex;
public Student(String sname, String sex) {
super();
this.sname = sname;
this.sex = sex;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
} - }
第三步:配置映射文件Student.hbm.xml,这里需要注意的是这个配置文件的名字一定要和你写的那个类名字相同(包括大小写),具体配置如下: - <?xml version="1.0" encoding="GBK"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping> - //name后面是导入你吓得Student类
<class name="com.su02.teacheapp.hibernate.po.Student">
<id name="id"> - //uuid是生成一个16进制的32的字符串做主键
<generator class="uuid"/>
</id> - //这里的name都是获取你的Student类里面的变量作为创建表中的字段
<property name="sname"/>
<property name="sex"/>
</class>
</hibernate-mapping> - 第四步:就开始下一个测试类来测试你的表是不创建成功了
- //需要注意的是这个测试类一定要继承TestCase
- package com.su02.teacheapp.tests.hib;
- import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport; - import junit.framework.TestCase;
- public class StudentTest extends TestCase {
public void testCreate(){
Configuration config=new Configuration().configure();
SchemaExport schemaExport=new SchemaExport(config);
schemaExport.create(true, true);
}
} - 好了,一个简单的Hibernate创建表就完成了,看明白后就自己测试一下,看看你的表示不创建成功!
Hibernate初学,实现创建数据库表
最新推荐文章于 2021-07-05 08:53:35 发布