lvjian700
9/5/2012 - 2:26 AM

Export Database Schema using hibernate tools

Export Database Schema using hibernate tools

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

<hibernate-configuration>

	<session-factory>
		<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
		<property name="hibernate.connection.url">jdbc:sqlserver://192.168.1.18:1433;DatabaseName=notice_pro</property>
		<property name="hibernate.connection.username">sa</property>
		<property name="hibernate.connection.password"></property>
		<property name="hibernate.connection.pool.size">20</property>
		<property name="hibernate.show_sql">true</property>
		<property name="jdbc.fetch_size">50</property>
		<property name="jdbc.batch_size">25</property>
		<property name="jdbc.use_scrollable_resultset">false</property>
		<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
		
		<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> 
		<property name="hibernate.cache.use_second_level_cache">false</property> 
		<property name="hibernate.cache.use_query_cache">false</property>
		
		
		<mapping resource="cn/com/dayang/auth/shiro/entity/NetworkPath.hbm.xml"/>
		<mapping resource="cn/com/dayang/auth/shiro/entity/Column.hbm.xml"/>
		<mapping resource="cn/com/dayang/workflow/entity/WorkflowBean.hbm.xml"/>
		<mapping resource="cn/com/dayang/workflow/entity/WorkflowHistory.hbm.xml"/>
		<mapping resource="cn/com/dayang/auth/shiro/entity/ShiroUser.hbm.xml"/>
		<mapping resource="cn/com/dayang/auth/shiro/entity/Role.hbm.xml"/>
		<mapping resource="cn/com/dayang/auth/shiro/entity/Permission.hbm.xml"/>

	</session-factory>


</hibernate-configuration>
<?xml version="1.0" encoding="utf-8" ?>
<project name="biandan3" default="compile" basedir=".">
	 <description>The biandan3 project ant script tools</description>
     <property environment="env"/> 
     <property name="src.java" value="src/java" />
     <property name="src.groovy" value="src/groovy" />
     <property name="src.res" value="src/resource" />
     
     <property name="test.java" value="test/java/test" />
     <property name="test.res" value="test/java/resource" />
	 
	 
	 <property name="tools.java" value="tools/java" />
  
     <property name="war.dir" value="war" />
     <property name="build.dir" value="${war.dir}/WEB-INF" />
     <property name="classes.dir" value="${build.dir}/classes" />    
     <property name="lib.dir" value="${build.dir}/lib"/>

     <property name="remote.driver" value="\\192.168.1.42\webapps" /> 

     <!-- 设置main函数所在类 -->
    
     <!-- 定义classpath -->
     <path id="classpath">
          <fileset dir="${lib.dir}" includes="**/*.jar" />
     </path>

     <path id="test-classpath">
          <fileset dir="${lib.dir}" includes="**/*.jar" />
          <fileset dir="${classes.dir}" includes="**/*.class" />
     </path>
    
     <!-- 创建构建目录,用于存放构建生成的文件 -->
     <target name="init" description="Initialized classpath folder">
          <mkdir dir="${classes.dir}"/>
     </target>
    
     <!-- 编译 -->
     <target name="compile" depends="init" description="compile project">
          <mkdir dir="${classes.dir}"/>
          <javac srcdir="${src.java};${src.groovy};${src.res};${test.java};${test.res};${tools.java}" destdir="${classes.dir}"
               classpathref="classpath">
               <include name="**/*.java" />
               <compilerarg line="-encoding UTF-8 "/>               
          </javac>
          <!-- copy properties file to classpath -->
          <copy todir="${classes.dir}">
               <fileset dir="${src.java}" excludes="**.*.jar" />
          </copy>
          <copy todir="${classes.dir}">
               <fileset dir="${src.groovy}" excludes="**.*.jar" />
          </copy>
          <copy todir="${classes.dir}">
               <fileset dir="${src.res}" excludes="**.*.jar" />
          </copy>
          <copy todir="${classes.dir}">
             <fileset dir="${test.java}" excludes="**.*.jar" />
          </copy>
          <copy todir="${classes.dir}">
             <fileset dir="${test.res}" excludes="**.*.jar" />
          </copy> 
          <copy todir="${classes.dir}">
             <fileset dir="${tools.java}" excludes="**.*.jar" />
          </copy> 
     </target>
    
     <target name="stop" description="stop tomcat on Mac OS [lvjian]">
         <exec executable="/Users/lvjian/tomcat6/bin/shutdown.sh" />
     </target>
     <target name="start" description="startup tomcat on Mac OS [lvjian]">
         <exec executable="/Users/lvjian/tomcat6/bin/startup.sh" />
     </target>
    
     <target name="clean" description="delete classes folder">
          <echo>clean path: ${classes.dir}</echo>
          <delete dir="${classes.dir}"/>
     </target>
	 
	<target name="dbhelp" depends="compile" description="help [hibernate export tools]">
		<java fork="true" classname="dayang.tools.db.HibernateSchemaExport"
				classpathref="test-classpath">
			<classpath path="${classes.dir}"/>
			<arg value="-h" />
		</java>		
	</target>
	 
	<target name="dbcreate" depends="compile" 
			description="create database [hibernate export tools]">
			
		<java fork="true" classname="dayang.tools.db.HibernateSchemaExport"
				classpathref="test-classpath">
			<classpath path="${classes.dir}"/>
			<arg value="-a" />
			<arg value="create" />
			<arg value="-f" />
			<arg value="dayang/tools/db/workflow.cfg.xml" />
			
		</java>
	</target>
	
	<target name="dbupdate" depends="compile"
			description="update database [hibernate export tools]">
			
		<java fork="true" classname="dayang.tools.db.HibernateSchemaExport"
				classpathref="test-classpath">
			<classpath path="${classes.dir}"/>
			<arg value="-a" />
			<arg value="update" />
			<arg value="-f" />
			<arg value="dayang/tools/db/workflow.cfg.xml" />
		</java>
	</target>
     
</project>
package dayang.tools.db;

import java.net.URL;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;

public class HibernateSchemaExport {
	
	static final String A_CREATE = "create";
	static final String A_UPDATE = "update";
	
	static Configuration config = null;
	
	static Options opts = new Options();
	
	static {
		opts.addOption("h", "help", false, "the command help");
		opts.addOption("a", "action", true, "create | update database tables.");
		opts.addOption("f", "cfgfile", true, 
				"the hibernate.cfg.xml file name.");
	}
	/**
	 * 根据cfg文件,生成数据库
	 * @param args
	 * cfg.xml file path
	 * @throws ParseException 
	 */
	public static void main(String[] args) throws ParseException { 
		
		CommandLineParser parser = new PosixParser();
		CommandLine cl = parser.parse(opts, args);
		
		
		if(cl.hasOption("h")) {
			 
			printHelp(opts);
			 
			return;
		}
		
		String action = cl.getOptionValue("action");
		String cfgFilePath = cl.getOptionValue("cfgfile");
		
		System.out.println("Execute ...");
		System.out.print("do action:");
		System.out.println(action);
		System.out.print("Hibernate configuration file:");
		System.out.println(cfgFilePath);
		
		URL path = ClassLoader.getSystemResource(cfgFilePath);
		System.out.println("getResource, the hibernate config file path");
		System.out.println(path);
		
		config = new Configuration().configure(path);
		
		if(config == null) {
			System.err.println("Can not found hibernate config file. \n Please check your path");
			System.err.println(cfgFilePath);
			
			return;
		}
		
		if(action.equalsIgnoreCase(A_CREATE)) {
			System.out.println("Do create database tables process...");
			doCreate(config);
			
		} else if(action.equalsIgnoreCase(A_UPDATE)) {
			System.out.println("Do update database tables proces...");
			doUpdate(config);
		}		

	}
	
	static void doUpdate (Configuration config) {
		SchemaUpdate schemaUpdate = new SchemaUpdate(config);
		schemaUpdate.execute(true, true);
	}
	
	static void doCreate(Configuration config) {
		SchemaExport schemaExport = new SchemaExport(config);
		schemaExport.create(true, true);
	}
	
	static void printHelp(Options opts) {
		HelpFormatter hf = new HelpFormatter();
		hf.printHelp("Using Hibernate Schema Tools, to create or update database schema.", opts);
	}
}