Hibernate Tools生成注释
获得源码的方法:
1.建立一个maven项目.
2.pox.xml修改为:
<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.pandy</groupId><artifactId>hibernate-tools</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>hibernate-tools</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-tools</artifactId><version>4.0.0-CR1</version></dependency></dependencies><build><plugins><plugin><!-- 注解支持,jdk5才具有的新特性,我们需要设置compile插件,具体可以参考Setting the -source and -target of the Java Compiler,根据说明,我们继续向pom文件中加入 --><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>5</source><target>5</target></configuration></plugin><plugin><!-- 我们想将所有的依赖库都打包,直接交给用户,这样用户不需要在做其他设置了,这里需要使用Assembly插件了,其说明参考Pre-defined Descriptor Files,这个参考文件也说明了有四种默认定义的打包方式,我们选择jar-with-dependencies,继续添加pom文件 --><artifactId>maven-assembly-plugin</artifactId><configuration><descriptorRefs><descriptorRef>jar-with-dependencies</descriptorRef></descriptorRefs></configuration></plugin></plugins></build></project>
public void readFromJDBC(String catalog, String schema) {JDBCBinder binder = new JDBCBinder(this, buildSettings(), createMappings(), revEngStrategy);binder.readFromDatabase(catalog, schema, buildMapping(this));}
<property name="hibernatetool.metadatadialect">org.hibernate.cfg.reveng.dialect.SQLServer2008MetaDataDialect</property>,
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- 连接数据库信息 --><property name="hibernate.bytecode.use_reflection_optimizer">false</property><property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property><property name="hibernate.connection.password">sa</property><property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;databaseName=Test</property><property name="hibernate.connection.username">sa</property><property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property><property name="hibernate.search.autoregister_listeners">false</property><!-- 代码生成信息 info --><property name="hibernatetool.metadatadialect">org.hibernate.cfg.reveng.dialect.SQLServer2008MetaDataDialect</property><!-- 自定义信息 --><property name="custom.package">com</property><property name="custom.one2many">false</property><property name="custom.many2one">true</property><property name="custom.many2many">true</property><property name="custom.detectOptimisticLock">true</property><property name="custom.catlog">Test</property><property name="custom.schema">dbo</property><property name="custom.isAnnotation">true</property><property name="custom.genPojo">true</property><property name="custom.genDao">true</property><property name="custom.outputDir">D:\\workspace\\CodeGenerator\\src</property></session-factory></hibernate-configuration>
import java.io.File;import java.util.Properties;import org.hibernate.cfg.Configuration;import org.hibernate.cfg.JDBCMetaDataConfiguration;import org.hibernate.cfg.reveng.DefaultReverseEngineeringStrategy;import org.hibernate.cfg.reveng.ReverseEngineeringSettings;import org.hibernate.tool.hbm2x.DAOExporter;import org.hibernate.tool.hbm2x.DAONewExporter;import org.hibernate.tool.hbm2x.POJOExporter;public class RunHibernateTools {/** * @param args */public void run() {String path = getClass().getResource("/").toString();if (path.startsWith("file:"))path = path.substring("file:".length() + 1);String fileName = path + "config/hibernate.cfg.xml";File file = new File(fileName);if (!file.exists()) {throw new RuntimeException("找不到配置文件");}// 直接给绝对路径会出问题Configuration xmlcfg = new Configuration().configure(file);JDBCMetaDataConfiguration cfg = new JDBCMetaDataConfiguration();Properties properties = xmlcfg.getProperties();cfg.setProperties(properties);DefaultReverseEngineeringStrategy configurableNamingStrategy = new DefaultReverseEngineeringStrategy();configurableNamingStrategy.setSettings(new ReverseEngineeringSettings(configurableNamingStrategy).setDefaultPackageName(getString(properties, "custom.package", "com"))// 要生成的包名.setCreateCollectionForForeignKey(getBoolean(properties, "custom.one2many", false))// 是否生成many-to-one的在one端的集合类,// 就是一对多的关系.setCreateManyToOneForForeignKey(getBoolean(properties, "custom.many2one", true))// 是否生成many-to-one.setDetectManyToMany(getBoolean(properties, "custom.many2many", true))// 是否生成many-to-many.setDetectOptimisticLock(getBoolean(properties, "custom.detectOptimisticLock", true)) // 乐观锁对象?);cfg.setReverseEngineeringStrategy(configurableNamingStrategy);// cfg.readFromJDBC();// 不区分schema和catlog的话,容易碰到错误.cfg.readFromJDBC(getString(properties, "custom.catlog", "Test"), getString(properties, "custom.schema", "dbo"));// 只从数据的这些信息生成cfg.buildMappings();if (getBoolean(properties, "custom.genPojo", true)) {POJOExporter exporter = new POJOExporter(cfg, getOutputDir(properties));if (getBoolean(properties, "custom.isAnnotation", true)) {exporter.getProperties().setProperty("ejb3", "true");// ejb3注解exporter.getProperties().setProperty("jdk5", "true");// jdk5语法(主要是集合类的泛型处理)}exporter.start();}if (getBoolean(properties, "custom.genDao", false)) {DAOExporter daoExporter = new DAOExporter(cfg, getOutputDir(properties));daoExporter.start();}// if (getBoolean(properties, "custom.genDao", false)) {// DAONewExporter daoExporter = new DAONewExporter(cfg,// getOutputDir(properties));// daoExporter.start();// }// QueryExporter queryExporter = new QueryExporter();// queryExporter.setConfiguration(cfg);// queryExporter.setOutputDirectory(getOutputDir(properties));// queryExporter.start();}private File getOutputDir(Properties properties) {File file = new File(getString(properties, "custom.outputDir", "/"));// 生成项目的物理位置(跟目录,tools会自动根据pacakge建立相应路径)return file;}private static boolean getBoolean(Properties properties, String key, boolean defaultValue) {String val = properties.getProperty(key);if (isBlank(val)) {return defaultValue;}return Boolean.valueOf(val);}private static String getString(Properties properties, String key, String defaultValue) {String val = properties.getProperty(key);if (isBlank(val)) {return defaultValue;}return val;}private static Integer getInteger(Properties properties, String key, Integer defaultValue) {String val = properties.getProperty(key);if (isBlank(val)) {return defaultValue;}return Integer.parseInt(val);}private static boolean isBlank(String val) {if (val == null || val.trim().length() == 0)return true;return false;}public static void main(String[] args) {System.out.println("----------------代码生成开始-----------------------");RunHibernateTools tools = new RunHibernateTools();tools.run();System.out.println("----------------代码生成完成-----------------------");}}