日期:2014-05-16 浏览次数:20687 次
1、新建Web Project工程
2、导入所需jar包

3、Student.java
package com.itmyhome;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name="T_STUDENT")
public class Student extends BizEntity{
private String name;
private String score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
Teacher.java
package com.itmyhome;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name="T_TEACHER")
public class Teacher extends BizEntity{
private String name;
private String title;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
BizEntity.java
package com.itmyhome;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
public class BizEntity {
private String id;
@Id @GeneratedValue(strategy=GenerationType.AUTO,generator="bizGenerator")
@GenericGenerator(strategy = "uuid", name = "bizGenerator")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
BizEntity.java是所有实体类的父类,id自动生成策略为uuid
4、hibernate.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="connection.url">jdbc:oracle:thin:@172.16.1.4:1521:orcl</property>
<property name="connection.username">username</property>
<property name="connection.password">123</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="current_session_context_class">thred</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">true</property>
</hibernate-mapping>
5、Test.java测试
package com.itmyhome;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//new SchemaExport(new AnnotationConfiguration().configure()).create(true, true); Teacher t = new Teacher();
t.setName("张三");
Configuration cfg = new AnnotationConfiguration();
SessionFactory factory =cfg.configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
}
}
SchemaExport自动生成数据表
运行程序: