日期:2014-05-16 浏览次数:20600 次
可以封装成一个java工具类,利用hibernate反向自动创建数据库,方便以后开发,提高效率。
创建数据库范例:
①主类
package com.hzp.test;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class ExportDB {
	public static void main(String[] args){
		//默认读取hibernate.cfg.xml配置文件
		Configuration cfg=new Configuration().configure();
		SchemaExport export=new SchemaExport(cfg);
		//创建数据库,并输出在控制台DDL语句
		export.create(true, true);
	}
}
②表的映射类
package com.hzp.hbq;
import java.util.Date;
public class Course {
	private int id;//课程id,主键
	private String name;//课程名称
	private Date time;//上课时间
	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 Date getTime() {
		return time;
	}
	public void setTime(Date time) {
		this.time = time;
	}
}
③数据库表映射文件
<?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 package="com.hzp.hbq">
	<class name="Course">
		<id name="id">
			<generator class="increment"></generator>
		</id>
		<property name="name"></property>
		<property name="time"></property>
	</class>
</hibernate-mapping>
④hibernate配置文件
<?xml version="1.0"?>
<!DOCTYPE hibernate-configuration PUBLIC 
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- 数据库驱动程序 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql:///courses</property>
		<!-- 数据库密码 -->
		<property name="hibernate.connection.password">515422</property>
		<!-- 数据库用户名 -->
		<property name="hibernate.connection.username">root</property>
		<!-- 数据库语言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 映射文件 -->
		<mapping resource="com/hzp/hbq/Course.hbq.xml"/>
	</session-factory>
</hibernate-configuration>
?