首页 > 技术文章 > hibernate通过配置文件生成数据库信息

wangkaipeng 2016-07-26 15:05 原文

hibernate可以通过配置文件在数据库生成相应的数据库信息。也可以把数据库的信息生成相应的代码(实体类操作类和映射文件)

下面是通过代码默认对hibernate.cfg.xml信息在数据库生成信息。事先要建好空的数据库

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC  
 3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
 4         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
 5           
 6 <hibernate-configuration>  
 7     <session-factory>  
 8         <property name="show_sql">true</property>  
 9         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  
10         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
11         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/guesswhat?useUnicode=true&amp;characterEncoding=utf8</property>  
12         <property name="hibernate.connection.username">root</property>  
13         <property name="hibernate.connection.password">1234</property>  
14         <mapping resource="com/us/google/domains/TUser.hbm.xml"/>  
15         <mapping resource="com/us/google/domains/TUrl.hbm.xml"/>  
16     </session-factory>  
17 </hibernate-configuration> 
hibernate.cfg.xml

列出一个表的单独配置信息

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC
 3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5 <hibernate-mapping package="com.us.google.domains">
 6     <class name="TUser" table="t_user">
 7         <id name="id" column="id">
 8             <generator class="identity"></generator>
 9         </id>
10         <property name="username" column="username"></property>
11         <property name="password" column="password"></property>
12     </class>
13 </hibernate-mapping> 
TUser.hbm.xml

执行操作

 1 package com.us.google.util;
 2 
 3 import org.hibernate.cfg.Configuration;
 4 import org.hibernate.tool.hbm2ddl.SchemaExport;
 5 
 6 public class GenerateSql {
 7 
 8     public static void main(String[] args) {
 9 
10         //默认读取hibernate.cfg.xml
11         Configuration cfg = new Configuration().configure();
12 
13         //生成并输出sql到文件(当前目录)和数据库
14         SchemaExport export = new SchemaExport(cfg);
15 
16         //true 在控制台打印sql语句,true 导入sql语句到数据库,即可执行
17         export.create(true, true);
18     }
19 }
GenerateSql

 

运行截图如下,在控制台打印出了执行的sql语句(建立表)

即在数据生成了信息。但是这样比较麻烦,等下说建好表如何生成代码

 

发现上面的写法过时了 现在是hibernate5 推荐下面的写法

ServiceRegistry serviceRegistry = (ServiceRegistry) new StandardServiceRegistryBuilder()
                .configure().build();
        MetadataImplementor metadataImplementor = (MetadataImplementor) new MetadataSources(
                serviceRegistry).buildMetadata();
        SchemaExport export = new SchemaExport(serviceRegistry,
                metadataImplementor);
        export.create(true, true);
Test.java

 

推荐阅读