hibernate tool 教下新手

标签: hibernate tool 教下 | 发表时间:2013-06-04 03:03 | 作者:wang102010
出处:http://blog.csdn.net

顺便研究了下hibernatetool 发现已经到了4.0beta,我用的是3.2的没有解决oracle的注释问题,4.0已经解决了

 源代码获取

http://anonsvn.jboss.org/repos/jbosstools/tags/

找一个你适合的分支


用svn工具下载下来


我用maven2创建了一个项目


添加了如下依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>ling2.parent</artifactId>
    <groupId>com.ling</groupId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <groupId>com.ling</groupId>
  <artifactId>ling2.autoproject</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-tools</artifactId>
      <version>4.0.0-CR1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
    	<groupId>org.eclipse.equinox</groupId>
    	<artifactId>registry</artifactId>
    	<version>3.3.0-v20070522</version>
    	<type>jar</type>
    	<scope>compile</scope>
    </dependency>
    <dependency>
    	<groupId>org.eclipse.core</groupId>
    	<artifactId>jobs</artifactId>
    	<version>3.3.0-v20070423</version>
    	<type>jar</type>
    	<scope>compile</scope>
    </dependency>
  </dependencies>
</project>

parent的依赖是我的公共依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.ling</groupId>
	<artifactId>ling2.parent</artifactId>
	<packaging>pom</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<modules>
		<module>ling2.core</module>
		<module>ling2.core.d5</module>
		<module>ling2.projecttemplate</module>
		<module>ling2.autoproject</module>
	</modules>
	<build>
		<defaultGoal>compile</defaultGoal>
		<finalName>ling2.core</finalName>
		<sourceDirectory>src/main/java</sourceDirectory>
		<resources>
			<!-- 控制资源文件的拷贝 -->
			<resource>
				<directory>src/main/resources</directory>
				<targetPath>${project.build.directory}</targetPath>
			</resource>
		</resources>
		<plugins>
			<!-- 设置源文件编码方式 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<defaultLibBundleDir>lib</defaultLibBundleDir>
					<source>1.6</source>
					<target>1.6</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- 打包jar文件时,配置manifest文件,加入lib包的jar依赖 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<classpathPrefix>lib/</classpathPrefix>
							<mainClass>.....MonitorMain</mainClass>
						</manifest>
					</archive>
				</configuration>
			</plugin>
			<!-- 拷贝依赖的jar包到lib目录 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<executions>
					<execution>
						<id>copy</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>
								${project.build.directory}/lib
							</outputDirectory>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<!-- 解决资源文件的编码问题 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- 打包source文件为jar文件 -->
			<plugin>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.1</version>
				<configuration>
					<attach>true</attach>
					<encoding>UTF-8</encoding>
				</configuration>
				<executions>
					<execution>
						<phase>compile</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>

	</build>
	<repositories>
		<repository>
			<id>bsdn-maven-repository</id>
			<url>http://nexus.bsdn.org/content/groups/public/</url>
		</repository>
	</repositories>
	<dependencies>
		<dependency>
			<artifactId>spring-orm</artifactId>
			<groupId>org.springframework</groupId>
			<version>3.2.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>3.2.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>3.2.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.2.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.2.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.2.1.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>com.bstek.dorado</groupId>
			<artifactId>dorado-core</artifactId>
			<version>7.2.4</version>
			<exclusions>
				<exclusion>
					<groupId>com.h2database</groupId>
					<artifactId>h2</artifactId>
				</exclusion>
				<exclusion>
					<artifactId>spring-context</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
				<exclusion>
					<artifactId>spring-aop</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
				<exclusion>
					<artifactId>spring-core</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
				<exclusion>
					<artifactId>spring-expression</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
				<exclusion>
					<artifactId>spring-beans</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
				<exclusion>
					<artifactId>spring-context-support</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
				<exclusion>
					<artifactId>spring-web</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
				<exclusion>
					<artifactId>spring-webmvc</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
				<exclusion>
					<artifactId>javassist</artifactId>
					<groupId>javassist</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4.1</version>
		</dependency>

		<dependency>
			<groupId>jexcelapi</groupId>
			<artifactId>jxl</artifactId>
			<version>2.6</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.2.1.Final</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ognl</groupId>
			<artifactId>ognl</artifactId>
			<version>3.0.6</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>3.2.2.RELEASE</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>3.1.4.RELEASE</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-core</artifactId>
			<version>3.1.4.RELEASE</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>3.1.3.RELEASE</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.5.4</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-c3p0</artifactId>
			<version>4.2.1.Final</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-ehcache</artifactId>
			<version>4.2.1.Final</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache-core</artifactId>
			<version>2.4.3</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
	</dependencies>
</project>

创建好的ling2.autoproject目录结构如下

运行maven命令

maven -install



相关jar包会自动放到../target/lib下

script 下的配置很重要,决定你能不能正常运行项目

我会当附件上传上去供大家借鉴


src.dir=../result
packagename=com.tplife.smp.channel.employee

决定生成的文件到那个目录,那个包下,

这些内容决定你编译需要哪些jar包和执行哪些动作

<?xml version="1.0" encoding="UTF-8"?>
<project basedir=".">
	<property file="build.properties">
	</property>
	<path id="toolslib">
		<!--<path location="../resources/libs/hibernate-tools.jar" />-->
		<pathelement location="../target/classes"/>
		<fileset dir="../target/lib">
			<include name="**/*.jar" />
		</fileset>
	</path>
	<target name="hibernatecode">
		<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" classpathref="toolslib" />
		<!-- destdir属性可以在各输出属性中分别指定,这里是全局指定 -->
		<hibernatetool destdir="${src.dir}" templatepath="../src/main/java">
			<!-- packagename表生成文件的存放包名 -->
			<jdbcconfiguration propertyfile="hibernate.properties" revengfile="hibernate.reveng.xml" packagename="${packagename}" />
			<!-- 生成.java文件 -->
			<hbm2java jdk5="true" ejb3="true"/>
			<hbm2hbmxml/>
			<!--<hbm2idao />
			<hbm2daoimpl />
			<hbm2iservice />
			<hbm2serviceimpl />
			<hbm2view />
			<hbm2viewmanager />
			<hbm2viewjsp />-->
		</hibernatetool>
	</target>
	<target name="schemaexport">
		<taskdef name="schemaexport" classname="org.hibernate.tool.hbm2ddl.SchemaExportTask" classpathref="toolslib" />
		<schemaexport properties="hibernate.properties" quiet="no" text="no" drop="no" delimiter=";" output="schema-export.sql">
			<fileset dir="${src.dir}">
				<include name="**/*.hbm.xml" />
			</fileset>
		</schemaexport>
	</target>

	<target name="schemaupdate">
		<taskdef name="schemaupdate" classname="org.hibernate.tool.hbm2ddl.SchemaUpdateTask" classpathref="toolslib" />
		<schemaupdate properties="hibernate.properties" quiet="no">
			<fileset dir="${src.dir}">
				<include name="**/*.hbm.xml" />
			</fileset>
		</schemaupdate>
	</target>

	<target name="schemavalidate">
		<taskdef name="schemavalidator" classname="org.hibernate.tool.hbm2ddl.SchemaValidatorTask" classpathref="toolslib" />
		<schemavalidator properties="hibernate.properties">
			<fileset dir="${src.dir}">
				<include name="**/*.hbm.xml" />
			</fileset>
		</schemavalidator>
	</target>

</project>

这些配置决定你的数据源配置

#hibernate.connection.driver_class=com.mysql.jdbc.Driver
#hibernate.connection.url=jdbc:mysql://localhost:3306/zhonghong?useUnicode=true&amp;characterEncoding=utf8
#hibernate.connection.username=root
#hibernate.connection.password=2009
#hibernate.dialect=org.hibernate.dialect.MySQLDialect
#hibernatetool.metadatadialect=org.hibernate.cfg.reveng.dialect.MySQLMetaDataDialect
hibernatetool.metadatadialect=org.hibernate.cfg.reveng.dialect.OracleMetaDataDialect
#If neither MySQL nor Oracle,please try below
#hibernatetool.metadatadialect=org.hibernate.cfg.reveng.dialect.JDBCMetaDataDialect
hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver
hibernate.connection.url=jdbc:oracle:thin:@localhost:1521:orclwin7
#hibernate.connection.url=jdbc:oracle:thin:@10.1.105.1:1521:ram
hibernate.connection.username=train
hibernate.connection.password=train
hibernate.dialect=org.hibernate.dialect.Oracle9iDialect

这些配置决定你要生成什么表

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>
	<type-mapping>
		<sql-type jdbc-type="NUMERIC" precision="15" hibernate-type="big_decimal"/>
 		<sql-type jdbc-type="NUMERIC" not-null="true" hibernate-type="long" />
 		<sql-type jdbc-type="NUMERIC" not-null="false" hibernate-type="java.lang.Long" />
		<sql-type jdbc-type="VARCHAR" length="1" hibernate-type="yes_no" />
		<sql-type jdbc-type="CHAR" length="1" hibernate-type="java.lang.String" />
		<sql-type jdbc-type="VARCHAR" hibernate-type="java.lang.String" />
		<sql-type jdbc-type="TIMESTAMP" length="6" hibernate-type="java.util.Date" />
		<!-- mysql -->
		<sql-type jdbc-type="SMALLINT" hibernate-type="java.lang.Integer" />
		<sql-type jdbc-type="INTEGER" length="1" hibernate-type="yes_no" />
		<sql-type jdbc-type="BIGINT" hibernate-type="java.lang.Long" />
			
	</type-mapping>
	
	<table-filter match-name="TBL_FILE"></table-filter>
	 <table-filter match-schema=".*" match-name="SS_.*"/>
	<table-filter match-schema=".*" match-name=".*" exclude="true"/>
 -->
</hibernate-reverse-engineering>
按如下方式执行生成代码


然后你就可以在这个基础上编写自己的内容了,比如我的dorado5模板

<hbm2idao />
<hbm2daoimpl />
<hbm2iservice />
<hbm2serviceimpl />
<hbm2view />
<hbm2viewmanager />
<hbm2viewjsp />

顺序是

HibernateToolTask中注册你自定义的新模板

这里的方法命名决定你

<hbm2idao />
<hbm2daoimpl />
<hbm2iservice />
<hbm2serviceimpl />
<hbm2view />
<hbm2viewmanager />
<hbm2viewjsp />

public ExporterTask createHbm2DAO(){
        ExporterTask generator= new Hbm2DAOExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2IDAO(){
        ExporterTask generator= new Hbm2IDAOExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2DAOImpl(){
        ExporterTask generator= new Hbm2DAOImplExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2IService(){
        ExporterTask generator= new Hbm2IServiceExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2ServiceImpl(){
        ExporterTask generator= new Hbm2ServiceImplExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2View(){
        ExporterTask generator= new Hbm2ViewExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2ViewManager(){
        ExporterTask generator= new Hbm2ViewTemplateExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2ViewJsp(){
        ExporterTask generator= new Hbm2ViewJspExporterTask(this);
        addGenerator( generator );
        return generator;
	}
以下以Hbm2ViewJsp为例子说明

/*
 * Created on 13-Feb-2005
 *
 */
package org.hibernate.tool.ant;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.Environment;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.PropertySet;
import org.hibernate.MappingException;
import org.hibernate.MappingNotFoundException;
import org.hibernate.cfg.Configuration;
import org.hibernate.util.StringHelper;

/**
 * @author max
 *
 */
public class HibernateToolTask extends Task {

	ConfigurationTask configurationTask;
	private File destDir;
	private List generators = new ArrayList();
	private Path classPath;
	private Path templatePath;
	private Properties properties = new Properties(); 	
	
	private void checkConfiguration() {
		if(configurationTask!=null) {
			throw new BuildException("Only a single configuration is allowed.");
		}
	}

	public ConfigurationTask createConfiguration() {
		checkConfiguration();
		configurationTask = new ConfigurationTask();
		return configurationTask;			
	}
	

	public JDBCConfigurationTask createJDBCConfiguration() {
		checkConfiguration();
		configurationTask = new JDBCConfigurationTask();
		return (JDBCConfigurationTask) configurationTask;			
	}
	
	public AnnotationConfigurationTask createAnnotationConfiguration() {
		checkConfiguration();
		configurationTask = new AnnotationConfigurationTask();
		return (AnnotationConfigurationTask) configurationTask;			
	}
	
	public JPAConfigurationTask createEjb3Configuration() {
		log( "<ejb3configuration> is deprecated. Use <jpaconfiguration> instead.", Project.MSG_WARN);
		checkConfiguration();
		configurationTask = new JPAConfigurationTask();
		return (JPAConfigurationTask) configurationTask;			
	}	
	
	public JPAConfigurationTask createJpaConfiguration() {
		checkConfiguration();
		configurationTask = new JPAConfigurationTask();
		return (JPAConfigurationTask) configurationTask;			
	}	
	
	public ExporterTask createHbm2DDL() {
		ExporterTask generator = new Hbm2DDLExporterTask(this);
		addGenerator( generator );
		return generator;
	}
	
	public ExporterTask createHbmTemplate() {
		ExporterTask generator = new GenericExporterTask(this);
		addGenerator( generator );
		return generator;
	}
	
	public ExporterTask createHbm2CfgXml() {
		ExporterTask generator = new Hbm2CfgXmlExporterTask(this);
		addGenerator( generator );
		
		return generator;
	}

	protected boolean addGenerator(ExporterTask generator) {
		return generators.add(generator);
	}
	
	public ExporterTask createHbm2Java() {
		ExporterTask generator = new Hbm2JavaExporterTask(this);
		addGenerator( generator );
		return generator;
	}
	
    public ExporterTask createHbm2HbmXml() {
        ExporterTask generator= new Hbm2HbmXmlExporterTask(this);
        addGenerator( generator );
        return generator;
    }
    
	public ExporterTask createHbm2Doc() {
        ExporterTask generator= new Hbm2DocExporterTask(this);
        addGenerator( generator );
        return generator;
    }
	
	/*public ExporterTask createHbm2Jsf(){
        ExporterTask generator= new Hbm2JsfGeneratorTask(this);
        generators.add(generator);
        return generator;
	}*/
	
	public ExporterTask createHbm2DAO(){
        ExporterTask generator= new Hbm2DAOExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2IDAO(){
        ExporterTask generator= new Hbm2IDAOExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2DAOImpl(){
        ExporterTask generator= new Hbm2DAOImplExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2IService(){
        ExporterTask generator= new Hbm2IServiceExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2ServiceImpl(){
        ExporterTask generator= new Hbm2ServiceImplExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2View(){
        ExporterTask generator= new Hbm2ViewExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2ViewManager(){
        ExporterTask generator= new Hbm2ViewTemplateExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public ExporterTask createHbm2ViewJsp(){
        ExporterTask generator= new Hbm2ViewJspExporterTask(this);
        addGenerator( generator );
        return generator;
	}
	
	public QueryExporterTask createQuery() {
		QueryExporterTask generator = new QueryExporterTask(this);
		generators.add(generator);
		return generator;
	}
	
	public HbmLintExporterTask createHbmLint() {
		HbmLintExporterTask generator = new HbmLintExporterTask(this);
		generators.add(generator);
		return generator;
	}
	
	
	/**
     * Set the classpath to be used when running the Java class
     *
     * @param s an Ant Path object containing the classpath.
     */
    public void setClasspath(Path s) {
		classPath = s;
    }

    /**
     * Adds a path to the classpath.
     *
     * @return created classpath
     */
    public Path createClasspath() {
		classPath = new Path(getProject() );
		return classPath;
    }

	
	public void execute() {
		if(configurationTask==null) {
			throw new BuildException("No configuration specified. <" + getTaskName() + "> must have one of the following: <configuration>, <jpaconfiguration>, <annotationconfiguration> or <jdbcconfiguration>");
		}
		log("Executing Hibernate Tool with a " + configurationTask.getDescription() );
		validateParameters();
		Iterator iterator = generators.iterator();
		
		AntClassLoader loader = getProject().createClassLoader(classPath);
		ExporterTask generatorTask = null;
		int count = 1;
		try {
			loader.setParent(this.getClass().getClassLoader() ); // if this is not set, classes from the taskdef cannot be found - which is crucial for e.g. annotations.
			loader.setThreadContextLoader();
			
			
			while (iterator.hasNext() ) {				
				generatorTask = (ExporterTask) iterator.next();
				log(count++ + ". task: " + generatorTask.getName() );
				generatorTask.execute();			
			}
		} catch (RuntimeException re) {
			reportException(re, count, generatorTask);
		} 
		finally {
			if (loader != null) {
				loader.resetThreadContextLoader();
				loader.cleanup();
			}            
		}
	}

	private void reportException(Throwable re, int count, ExporterTask generatorTask) {
		log("An exception occurred while running exporter #" + count + ":" + generatorTask.getName(), Project.MSG_ERR);
		log("To get the full stack trace run ant with -verbose", Project.MSG_ERR);
		
		log(re.toString(), Project.MSG_ERR);
		String ex = new String();
		Throwable cause = re.getCause();
		while(cause!=null) {
			ex += cause.toString() + "\n";
			if(cause==cause.getCause()) {
				break; // we reached the top.
			} else {
				cause=cause.getCause();
			}
		}
		if(StringHelper.isNotEmpty(ex)) {
			log(ex, Project.MSG_ERR);
		}

		String newbieMessage = getProbableSolutionOrCause(re);
		if(newbieMessage!=null) {
			log(newbieMessage);
		} 		
		
		if(re instanceof BuildException) {
			throw (BuildException)re;
		} else {
			throw new BuildException(re, getLocation());
		}
	}

	private String getProbableSolutionOrCause(Throwable re) {
		if(re==null) return null;
		
		if(re instanceof MappingNotFoundException) {
			MappingNotFoundException mnf = (MappingNotFoundException)re;
			if("resource".equals(mnf.getType())) {
				return "A " + mnf.getType() + " located at " + mnf.getPath() + " was not found.\n" +
						"Check the following:\n" +
						"\n" +
						"1) Is the spelling/casing correct ?\n" +
						"2)	Is " + mnf.getPath() + " available via the classpath ?\n" +
						"3) Does it actually exist ?\n";						
			} else {
				return "A " + mnf.getType() + " located at " + mnf.getPath() + " was not found.\n" +
				"Check the following:\n" +
				"\n" +
				"1) Is the spelling/casing correct ?\n" +
				"2)	Do you permission to access " + mnf.getPath() + " ?\n" +
				"3) Does it actually exist ?\n";	
			}
		}

		if(re instanceof ClassNotFoundException || re instanceof NoClassDefFoundError) {
			
			return "A class were not found in the classpath of the Ant task.\n" +
					"Ensure that the classpath contains the classes needed for Hibernate and your code are in the classpath.\n"; 			
			
		}
		
		if(re instanceof UnsupportedClassVersionError) {
			return "You are most likely running the ant task with a JRE that is older than the JRE required to use the classes.\n" +
					"e.g. running with JRE 1.3 or 1.4 when using JDK 1.5 annotations is not possible.\n" +
					"Ensure that you are using a correct JRE.";
		}
		
		
		
		if(re.getCause()!=re) {
			return getProbableSolutionOrCause( re.getCause() );					
		}
		
		return null;
	}

	private void validateParameters() {
		if(generators.isEmpty()) {
			throw new BuildException("No exporters specified in <hibernatetool>. There has to be at least one specified. An exporter is e.g. <hbm2java> or <hbmtemplate>. See documentation for details.", getLocation());
		} else {
			Iterator iterator = generators.iterator();
			
			while (iterator.hasNext() ) {
				ExporterTask generatorTask = (ExporterTask) iterator.next();
				generatorTask.validateParameters();			
			}
		}
	}

	/**
	 * @return
	 */
	public File getDestDir() {
		return destDir;
	}
	
	public void setDestDir(File file) {
		destDir = file;
	}

	/**
	 * @return
	 */
	public Configuration getConfiguration() {
		return configurationTask.getConfiguration();
	}

	public void setTemplatePath(Path path) {
		templatePath = path;
	}
	
	public Path getTemplatePath() {
		if(templatePath==null) {
			templatePath = new Path(getProject()); // empty path
		}
		return templatePath;
	}

	public Properties getProperties() {
		Properties p = new Properties();
		p.putAll(getConfiguration().getProperties());
		p.putAll(properties);
		return p;
	}
	
	public void addConfiguredPropertySet(PropertySet ps) {
		properties.putAll(ps.getProperties());
	}
	
	public void addConfiguredProperty(Environment.Variable property) {
		properties.put(property.getKey(), property.getValue());
	}
	
}
写一个继承
Hbm2ViewJspExporterTask  extends Hbm2JavaExporterTask 
package org.hibernate.tool.ant;

import org.hibernate.tool.hbm2x.DAOExporter;
import org.hibernate.tool.hbm2x.DAOImplExporter;
import org.hibernate.tool.hbm2x.Exporter;
import org.hibernate.tool.hbm2x.IDAOExporter;
import org.hibernate.tool.hbm2x.ServiceImplExporter;
import org.hibernate.tool.hbm2x.ViewExporter;
import org.hibernate.tool.hbm2x.ViewJspExporter;
import org.hibernate.tool.hbm2x.ViewTemplateExporter;

/**
 * @author Dennis Byrne
 */
public class Hbm2ViewJspExporterTask extends Hbm2JavaExporterTask {

	public Hbm2ViewJspExporterTask(HibernateToolTask parent) {
		super(parent);
	}
	
	protected Exporter configureExporter(Exporter exp) {
		ViewJspExporter exporter = (ViewJspExporter)exp;
		super.configureExporter(exp);
		return exporter;
	}
	
	protected Exporter createExporter() {
		return new ViewJspExporter(parent.getConfiguration(), parent.getDestDir()) ;
	}

	public String getName() {
		return "hbm2viewjsp (Generates a set of viewjsp)";
	}

}

这里决定你ftl的模板的相对位置

package org.hibernate.tool.hbm2x;

import java.io.File;
import java.util.Map;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2x.pojo.POJOClass;

public class ViewJspExporter extends POJOExporter {

    private static final String DAO_DAOHOME_FTL = "dao/ViewJsp.ftl";

    private String sessionFactoryName = "SessionFactory";

    public ViewJspExporter() {
    }
    
    public ViewJspExporter(Configuration cfg, File outputdir) {
        super(cfg, outputdir);        
    }

    protected void init() {
    	super.init();
    	setTemplateName(DAO_DAOHOME_FTL);
    	setFilePattern("{package-name}/view/jsp/{class-name}Manager.jsp");    	    	
    }
    
    protected void exportComponent(Map additionalContext, POJOClass element) {
    	// noop - we dont want components
    }

	public String getSessionFactoryName() {
		return sessionFactoryName;
	}

	public void setSessionFactoryName(String sessionFactoryName) {
		this.sessionFactoryName = sessionFactoryName;
	}

	protected void setupContext() {
		getProperties().put("sessionFactoryName", getSessionFactoryName());
		super.setupContext();		
	}
	
	public String getName() {
		return "hbm2view";
	}

	
}

ftl模板内容
<#assign classbody>
<#assign declarationName = pojo.importType(pojo.getDeclarationName())>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="http://www.bstek.com/dorado" prefix="d"%>
<html>
<head>
<title>管理</title>
</head>
<body scroll="yes">
<d:View config="${pojo.getPackageName()}.view.${declarationName}Manager">
	<d:Layout type="border" height="100%">
		<d:Pane position="top">
					<d:Layout type="Vflow">
						<d:Pane>
							<d:AutoForm id="frmQuery" />
						</d:Pane>
						<d:Pane>
							<d:Layout type="Hflow">
								<d:Pane>
							<d:Button id="btnQuery" />
							</d:Pane>
							<d:Pane>
								<d:Button id="btnReset" />
							</d:Pane>
							<d:Pane>
								<d:Button id="btnNew" />
							</d:Pane>
							<d:Pane>
								<d:Button id="btnDelete" />
							</d:Pane>
							<d:Pane>
								<d:Button id="buttonModify" />
							</d:Pane>
							</d:Layout>
						</d:Pane>
					</d:Layout>
		</d:Pane>
		<d:Pane position="center">
			<d:DataTable id="tblEntity" />
		</d:Pane>
		<d:Pane position="bottom">
			<d:PagePilot id="pageEntity" />
			<table cellpadding="5">
				<tr>
					<td nowrap bgcolor="#F5F7F9">数据提取模式:</td>
					<td bgcolor="#F5F7F9"><d:RadioGroup id="editorDataMode" /></td>
					<td bgcolor="#F5F7F9"><d:Button id="buttonExcel" /></td>
				</tr>
			</table>
		</d:Pane>
	</d:Layout>
	<d:SubWindow id="win1" width="450px" height="150px" draggable="true"
		resizable="true" status="hidden" showMinimizeButton="false"
		showMaximizeButton="false" showCloseButton="false">
		<d:Layout type="border">
			<d:Pane position="top">
				<d:AutoForm id="frmEntity" />
			</d:Pane>
			<d:Pane position="center" align="right">
				<d:Layout type="Hflow">
					<d:Pane>
						<d:Button id="btnSave" />
					</d:Pane>
					<d:Pane>
						<d:Button id="btnCancel" />
					</d:Pane>
				</d:Layout>
			</d:Pane>
		</d:Layout>
	</d:SubWindow>
</d:View>
</body>
</html>
</#assign>
${classbody}


作者:wang102010 发表于2013-6-4 3:03:19 原文链接
阅读:24 评论:0 查看评论

相关 [hibernate tool 教下] 推荐:

hibernate tool 教下新手

- - CSDN博客推荐文章
顺便研究了下hibernatetool 发现已经到了4.0beta,我用的是3.2的没有解决oracle的注释问题,4.0已经解决了. 我用maven2创建了一个项目. parent的依赖是我的公共依赖

新的 repo tool

- sun409 - 阿偉的個人天地
由於八月底發生 kernel.org 被 hacked 的事件,導致 kernel.org 底下的服務全面停擺,包括 Google 的 Android git server android.git.kernel.org,至今仍未恢復. 當然也導致目前無法下載最新的 Android source code.

chrome developer tool 调试技巧

- - Taobao UED Team
这篇文章是根据目前 chrome 稳定版(19.0.1084.52 m)写的, 因为 google 也在不断完善chrome developer tool, 所以 chrome 版本不同可能稍有差别. 一些快捷键也是 windows 上的, mac 下的应该大同小异.. 常规的断点相关的 breakpoint/conditional-breakpoint/call-stack/watch-expressions 等就不涉及了..

Hibernate面试题

- - ITeye博客
什么是Hibernate的并发机制. Hibernate并发机制:. a、Hibernate的Session对象是非线程安全的,对于单个请求,单个会话,单个的工作单元(即单个事务,单个线程),它通常只使用一次,. 如果一个Session 实例允许共享的话,那些支持并发运行的,例如Http request,session beans将会导致出现资源争用.

Hibernate Lazy属性

- - 博客园_首页
  Hibernate 的延迟加载(lazy load)是一个被广泛使用的技术. 这种延迟加载保证了应用只有在需要时才去数据库中抓取相应的记录. 通过延迟加载技术可以避免过多、过早地加载数据表里的数据,从而降低应用的内存开销. Hibernate 的延迟加载本质上就是代理模式的应用,当程序通过 Hibernate 装载一个实体时,默认情况下,Hibernate 并不会立即抓取它的集合属性、关联实体所以对应的记录,而是通过生成一个代理来表示这些集合属性、关联实体,这就是代理模式应用带来的优势.

Hibernate 缓存

- - ITeye博客
1数据缓存:(date caching) 是一种将数据暂时存于内存缓存去中的技术,缓存通常是影响系统性能的关键因素. 2.ORM的数据缓存策略有3中.   1.事务级缓存:  分为 数据库事务和 应用级事务,是基于Session的生命周期的实现,每个session都会在内部维持一个数据缓存, 随session的创建和消亡.

hibernate优化

- - 开源软件 - ITeye博客
原文 http://developer.51cto.com/art/200906/129539.htm. 文章分为十三个小块儿对Hibernate性能优化技巧进行总结性分析,分析如下:. 一、在处理大数据量时,会有大量的数据缓冲保存在Session的一级缓存中,这缓存大太时会严重显示性能,所以在使用Hibernate处理大数据量的,可以使用session.

JPA & Hibernate 注解

- - CSDN博客编程语言推荐文章
必须,name为可选,对应数据库中一的个表 . 可选,通常和@Entity配合使用,只能标注在实体的class定义处,表示实体对应的数据库表的信息 . name:可选,表示表的名称.默认地,表名和实体名称一致,只有在不一致的情况下才需要指定表名 . catalog:可选,表示Catalog名称,默认为Catalog(""). .

hibernate 大对象类型的hibernate映射

- - CSDN博客推荐文章
在 Java 中, java.lang.String 可用于表示长字符串(长度超过 255), 字节数组 byte[] 可用于存放图片或文件的二进制数据. 此外, 在 JDBC API 中还提供了 java.sql.Clob 和 java.sql.Blob 类型, 它们分别和标准 SQL 中的 CLOB 和 BLOB 类型对应.

JBoss发布Hibernate 4.0

- - InfoQ cn
近日, JBoss发布了流行的对象/关系(O/R)映射框架 Hibernate. Hibernate 4主要的新特性如下所示:. 引入了“Services”API. 提供了更棒的日志,支持 i18n与消息编码(通过JBoss Logging而非 slf4j). 为 OSGi支持做好了准备.