利用hibernate反向自动创建数据库

 

可以封装成一个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>


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值