hibernate通过实体类和hbm.xml生成数据库表

    由于某些原因,上某网站找了一个适合自己需求的开源项目,框架为ssh,难耐没有sql脚本,于是想到hibernate的正向生成数据库表,首先做好准备工作:

    1、建好对应的数据库

    2、需要一个hibernate.cfg.xml的配置文件(和你用validator逆向生成实体类用的差不多),代码如下:

    

<?xml version="1.0" encoding='utf-8'?>
<!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://localhost:3306/xx?useUnicode=true&amp;characterEncoding=UTF8
        </property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <mapping resource="com/xx/xx.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

3、最后需要一个工具类来生成表,代码如下:

public static void main(String[] args) {
	//读取配置文件
	Configuration cfg = new Configuration().configure("com/hibernate.cfg.xml");
	// 生成ddl文件,并在控制台输出
	SchemaExport export = new SchemaExport(cfg);
	export.create(true, true);
}

猜你喜欢

转载自blog.csdn.net/weixin_39841589/article/details/82253597