国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
讓Hibernate生成的DDL腳本自動增加注釋
                  我們知道可以通過Hibernate對象自動生成DDL建表語句,通過PowerDesigner工具可以反向工程生成數(shù)據(jù)字典,但是在生成的DDL中一直不能寫上中文的注釋,這就使我們生成的數(shù)據(jù)字典不具有可用性。

這個假期宅在家里調(diào)試代碼,發(fā)現(xiàn)Hibernate的Dialect,Table,Column的映射中已經(jīng)做了comment的處理,只是Hibernate團隊認(rèn)為這個功能的重要性太小,一直沒有時間提供這個需求,于是就自己動手實現(xiàn)這個功能了,這可是使用我們的數(shù)據(jù)對象代碼與數(shù)據(jù)字典文檔同步的關(guān)鍵一環(huán)?。?/p>

通過對Hibernate代碼的跟蹤發(fā)現(xiàn)了處理映射的邏輯是在代碼AnnotationBinder中,我們不需要在運行期間處理comment,只是在用SchemaExport時處理就可以,于是簡單的實現(xiàn)了此功能:

1. 增加一個注解 @Comment("這是表的說明,也可以是字段的說明"),適用在類名和屬性名

2. 復(fù)制org.hibernate.cfg.AnnotationBuilder代碼為org.hibernate.cfg.MyAnnotationBuilder,處理注解@Comment

3. 復(fù)制org.hibernate.cfg.Configuration為org.hibernate.cfg.MyConfiguration,將AnnotationBuilder的調(diào)用換成MyAnnotationBuilder

3. 實現(xiàn)SchemaExportTool類,傳入MyConfiguration處理Hibernate對象的映射關(guān)系,并生成DDL

 

以上思路在基于Hibernate 4.2.3版本在MySql 5.1上測試成功,因為代碼只是在開發(fā)期運行,不需要良好的結(jié)構(gòu)和優(yōu)化,所以只是簡單實現(xiàn)了,需要此功能的朋友可以自己實現(xiàn)。

 

以下是處理結(jié)果示例:

  1. @Entity  
  2. @Table(name = "AuditRecord_")  
  3. @Comment("系統(tǒng)審計表")  
  4. @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)  
  5. public class AuditRecord implements Serializable {  
  6.   
  7.     private static final long serialVersionUID = 8844543936912679937L;  
  8.     @Id  
  9.     @GeneratedValue  
  10.     @Comment("ID主鍵")  
  11.     private Long id;  
  12.     @Comment("審計類型")  
  13.     @Column(length = 30)  
  14.     private String auditType;  
  15.     @Comment("操作人")  
  16.     @ManyToOne  
  17.     @JoinColumn(name = "userId")  
  18.     private Passport operator;  
  19.     // 操作簡述   
  20.     @Comment("操作簡述")  
  21.     @Column(length = 4000)  
  22.     private String description;  
  23.     @Comment("創(chuàng)建時間")  
  24.     private Date creationTime;  
  25. }  
  1. @Entity  
  2. @Table(name = "AuditRecord_")  
  3. @Comment("系統(tǒng)審計表")  
  4. @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)  
  5. public class AuditRecord implements Serializable {  
  6.   
  7.     private static final long serialVersionUID = 8844543936912679937L;  
  8.     @Id  
  9.     @GeneratedValue  
  10.     @Comment("ID主鍵")  
  11.     private Long id;  
  12.     @Comment("審計類型")  
  13.     @Column(length = 30)  
  14.     private String auditType;  
  15.     @Comment("操作人")  
  16.     @ManyToOne  
  17.     @JoinColumn(name = "userId")  
  18.     private Passport operator;  
  19.     // 操作簡述  
  20.     @Comment("操作簡述")  
  21.     @Column(length = 4000)  
  22.     private String description;  
  23.     @Comment("創(chuàng)建時間")  
  24.     private Date creationTime;  
  25. }  


生成的DDL如下:

  1. create table audit_record_ (  
  2.         id bigint not null auto_increment comment 'ID主鍵',  
  3.         audit_type varchar(30) comment '審計類型',  
  4.         creation_time datetime comment '創(chuàng)建時間',  
  5.         description longtext comment '操作簡述',  
  6.         user_id bigint comment '操作人',  
  7.         primary key (id)  
  8.     ) comment='系統(tǒng)審計表';  
  1. create table audit_record_ (  
  2.         id bigint not null auto_increment comment 'ID主鍵',  
  3.         audit_type varchar(30) comment '審計類型',  
  4.         creation_time datetime comment '創(chuàng)建時間',  
  5.         description longtext comment '操作簡述',  
  6.         user_id bigint comment '操作人',  
  7.         primary key (id)  
  8.     ) comment='系統(tǒng)審計表';  


 

主要代碼片斷如下:

 

  1. import java.io.IOException;  
  2. import java.util.Properties;  
  3.   
  4. import javax.persistence.Embeddable;  
  5. import javax.persistence.Entity;  
  6. import javax.persistence.MappedSuperclass;  
  7.   
  8. import org.hibernate.MappingException;  
  9. import org.hibernate.cfg.MyConfiguration;  
  10. import org.hibernate.tool.hbm2ddl.SchemaExport;  
  11. import org.springframework.core.io.Resource;  
  12. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;  
  13. import org.springframework.core.io.support.ResourcePatternResolver;  
  14. import org.springframework.core.io.support.ResourcePatternUtils;  
  15. import org.springframework.core.type.classreading.CachingMetadataReaderFactory;  
  16. import org.springframework.core.type.classreading.MetadataReader;  
  17. import org.springframework.core.type.classreading.MetadataReaderFactory;  
  18. import org.springframework.core.type.filter.AnnotationTypeFilter;  
  19. import org.springframework.core.type.filter.TypeFilter;  
  20. import org.springframework.util.ClassUtils;  
  21.   
  22. public class SchemaExportTool extends MyConfiguration {  
  23.   
  24.     private static final long serialVersionUID = 1L;  
  25.   
  26.     private static final String RESOURCE_PATTERN = "/**/*.class";  
  27.   
  28.     private static final String PACKAGE_INFO_SUFFIX = ".package-info";  
  29.   
  30.     private static final TypeFilter[] ENTITY_TYPE_FILTERS = new TypeFilter[] {  
  31.             new AnnotationTypeFilter(Entity.class, false),  
  32.             new AnnotationTypeFilter(Embeddable.class, false),  
  33.             new AnnotationTypeFilter(MappedSuperclass.class, false) };  
  34.     private final ResourcePatternResolver resourcePatternResolver;  
  35.   
  36.     public SchemaExportTool() {  
  37.         this.resourcePatternResolver = ResourcePatternUtils  
  38.                 .getResourcePatternResolver(new PathMatchingResourcePatternResolver());  
  39.     }  
  40.   
  41.     public static void main(String[] args) {  
  42.         try {  
  43.             Properties p = new Properties();  
  44.             p.setProperty("hibernate.dialect",  
  45.                     "org.hibernate.dialect.MySQLDialect");  
  46.             SchemaExportTool cfg = new SchemaExportTool();  
  47.             cfg.addProperties(p);  
  48.             cfg.setNamingStrategy(new ImprovedMyNamingStrategy());  
  49.             cfg.scanPackage("com.share.passport.domain",  
  50.                     "com.share.authority.domain", "com.share.utils.domain");  
  51.   
  52.             SchemaExport se = new SchemaExport(cfg);  
  53.             if (null != args && args.length > 1)  
  54.                 if ("-f".equals(args[0]))  
  55.                     se.setOutputFile(args[1]);  
  56.                 else  
  57.                     se.setOutputFile("create_table.sql");  
  58.             else  
  59.                 se.setOutputFile("create_table.sql");  
  60.             se.setDelimiter(";");  
  61.             // se.drop(false, false);  
  62.             se.create(false, false);  
  63.   
  64.         } catch (Exception e) {  
  65.             e.printStackTrace();  
  66.         }  
  67.   
  68.     }  
  69.   
  70.     private SchemaExportTool scanPackage(String... packagesToScan) {  
  71.         try {  
  72.             for (String pkg : packagesToScan) {  
  73.                 String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX  
  74.                         + ClassUtils.convertClassNameToResourcePath(pkg)  
  75.                         + RESOURCE_PATTERN;  
  76.                 Resource[] resources = this.resourcePatternResolver  
  77.                         .getResources(pattern);  
  78.                 MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(  
  79.                         this.resourcePatternResolver);  
  80.                 for (Resource resource : resources) {  
  81.                     if (resource.isReadable()) {  
  82.                         MetadataReader reader = readerFactory  
  83.                                 .getMetadataReader(resource);  
  84.                         String className = reader.getClassMetadata()  
  85.                                 .getClassName();  
  86.                         if (matchesEntityTypeFilter(reader, readerFactory)) {  
  87.                             addAnnotatedClass(this.resourcePatternResolver  
  88.                                     .getClassLoader().loadClass(className));  
  89.                         } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {  
  90.                             addPackage(className.substring(  
  91.                                     0,  
  92.                                     className.length()  
  93.                                             - PACKAGE_INFO_SUFFIX.length()));  
  94.                         }  
  95.                     }  
  96.                 }  
  97.             }  
  98.             return this;  
  99.         } catch (IOException ex) {  
  100.             throw new MappingException(  
  101.                     "Failed to scan classpath for unlisted classes", ex);  
  102.         } catch (ClassNotFoundException ex) {  
  103.             throw new MappingException(  
  104.                     "Failed to load annotated classes from classpath", ex);  
  105.         }  
  106.     }  
  107.   
  108.     /** 
  109.      * Check whether any of the configured entity type filters matches the 
  110.      * current class descriptor contained in the metadata reader. 
  111.      */  
  112.     private boolean matchesEntityTypeFilter(MetadataReader reader,  
  113.             MetadataReaderFactory readerFactory) throws IOException {  
  114.         for (TypeFilter filter : ENTITY_TYPE_FILTERS) {  
  115.             if (filter.match(reader, readerFactory)) {  
  116.                 return true;  
  117.             }  
  118.         }  
  119.         return false;  
  120.     }  
  121.   
  122. }  
  1. import java.io.IOException;  
  2. import java.util.Properties;  
  3.   
  4. import javax.persistence.Embeddable;  
  5. import javax.persistence.Entity;  
  6. import javax.persistence.MappedSuperclass;  
  7.   
  8. import org.hibernate.MappingException;  
  9. import org.hibernate.cfg.MyConfiguration;  
  10. import org.hibernate.tool.hbm2ddl.SchemaExport;  
  11. import org.springframework.core.io.Resource;  
  12. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;  
  13. import org.springframework.core.io.support.ResourcePatternResolver;  
  14. import org.springframework.core.io.support.ResourcePatternUtils;  
  15. import org.springframework.core.type.classreading.CachingMetadataReaderFactory;  
  16. import org.springframework.core.type.classreading.MetadataReader;  
  17. import org.springframework.core.type.classreading.MetadataReaderFactory;  
  18. import org.springframework.core.type.filter.AnnotationTypeFilter;  
  19. import org.springframework.core.type.filter.TypeFilter;  
  20. import org.springframework.util.ClassUtils;  
  21.   
  22. public class SchemaExportTool extends MyConfiguration {  
  23.   
  24.     private static final long serialVersionUID = 1L;  
  25.   
  26.     private static final String RESOURCE_PATTERN = "/**/*.class";  
  27.   
  28.     private static final String PACKAGE_INFO_SUFFIX = ".package-info";  
  29.   
  30.     private static final TypeFilter[] ENTITY_TYPE_FILTERS = new TypeFilter[] {  
  31.             new AnnotationTypeFilter(Entity.class, false),  
  32.             new AnnotationTypeFilter(Embeddable.class, false),  
  33.             new AnnotationTypeFilter(MappedSuperclass.class, false) };  
  34.     private final ResourcePatternResolver resourcePatternResolver;  
  35.   
  36.     public SchemaExportTool() {  
  37.         this.resourcePatternResolver = ResourcePatternUtils  
  38.                 .getResourcePatternResolver(new PathMatchingResourcePatternResolver());  
  39.     }  
  40.   
  41.     public static void main(String[] args) {  
  42.         try {  
  43.             Properties p = new Properties();  
  44.             p.setProperty("hibernate.dialect",  
  45.                     "org.hibernate.dialect.MySQLDialect");  
  46.             SchemaExportTool cfg = new SchemaExportTool();  
  47.             cfg.addProperties(p);  
  48.             cfg.setNamingStrategy(new ImprovedMyNamingStrategy());  
  49.             cfg.scanPackage("com.share.passport.domain",  
  50.                     "com.share.authority.domain", "com.share.utils.domain");  
  51.   
  52.             SchemaExport se = new SchemaExport(cfg);  
  53.             if (null != args && args.length > 1)  
  54.                 if ("-f".equals(args[0]))  
  55.                     se.setOutputFile(args[1]);  
  56.                 else  
  57.                     se.setOutputFile("create_table.sql");  
  58.             else  
  59.                 se.setOutputFile("create_table.sql");  
  60.             se.setDelimiter(";");  
  61.             // se.drop(false, false);  
  62.             se.create(false, false);  
  63.   
  64.         } catch (Exception e) {  
  65.             e.printStackTrace();  
  66.         }  
  67.   
  68.     }  
  69.   
  70.     private SchemaExportTool scanPackage(String... packagesToScan) {  
  71.         try {  
  72.             for (String pkg : packagesToScan) {  
  73.                 String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX  
  74.                         + ClassUtils.convertClassNameToResourcePath(pkg)  
  75.                         + RESOURCE_PATTERN;  
  76.                 Resource[] resources = this.resourcePatternResolver  
  77.                         .getResources(pattern);  
  78.                 MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(  
  79.                         this.resourcePatternResolver);  
  80.                 for (Resource resource : resources) {  
  81.                     if (resource.isReadable()) {  
  82.                         MetadataReader reader = readerFactory  
  83.                                 .getMetadataReader(resource);  
  84.                         String className = reader.getClassMetadata()  
  85.                                 .getClassName();  
  86.                         if (matchesEntityTypeFilter(reader, readerFactory)) {  
  87.                             addAnnotatedClass(this.resourcePatternResolver  
  88.                                     .getClassLoader().loadClass(className));  
  89.                         } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {  
  90.                             addPackage(className.substring(  
  91.                                     0,  
  92.                                     className.length()  
  93.                                             - PACKAGE_INFO_SUFFIX.length()));  
  94.                         }  
  95.                     }  
  96.                 }  
  97.             }  
  98.             return this;  
  99.         } catch (IOException ex) {  
  100.             throw new MappingException(  
  101.                     "Failed to scan classpath for unlisted classes", ex);  
  102.         } catch (ClassNotFoundException ex) {  
  103.             throw new MappingException(  
  104.                     "Failed to load annotated classes from classpath", ex);  
  105.         }  
  106.     }  
  107.   
  108.     /** 
  109.      * Check whether any of the configured entity type filters matches the 
  110.      * current class descriptor contained in the metadata reader. 
  111.      */  
  112.     private boolean matchesEntityTypeFilter(MetadataReader reader,  
  113.             MetadataReaderFactory readerFactory) throws IOException {  
  114.         for (TypeFilter filter : ENTITY_TYPE_FILTERS) {  
  115.             if (filter.match(reader, readerFactory)) {  
  116.                 return true;  
  117.             }  
  118.         }  
  119.         return false;  
  120.     }  
  121.   
  122. }  

  1. /** 
  2.  * $Id:$ 
  3.  */  
  4. package com.share.utils.hibernate;  
  5.   
  6. import org.hibernate.annotations.common.reflection.XClass;  
  7. import org.hibernate.annotations.common.reflection.XProperty;  
  8. import org.hibernate.cfg.Ejb3Column;  
  9. import org.hibernate.mapping.PersistentClass;  
  10.   
  11. import com.share.annotations.Comment;  
  12.   
  13. public class CommentBinder {  
  14.     public static void bindTableComment(XClass clazzToProcess, PersistentClass persistentClass) {  
  15.         if (clazzToProcess.isAnnotationPresent(Comment.class)) {  
  16.             String tableComment = clazzToProcess.getAnnotation(Comment.class).value();  
  17.             persistentClass.getTable().setComment(tableComment);  
  18.   
  19.         }  
  20.     }  
  21.   
  22.     public static void bindColumnComment(XProperty property, Ejb3Column[] columns) {  
  23.         if (null != columns)  
  24.   
  25.             if (property.isAnnotationPresent(Comment.class)) {  
  26.                 String comment = property.getAnnotation(Comment.class).value();  
  27.                 for (Ejb3Column column : columns) {  
  28.                     column.getMappingColumn().setComment(comment);  
  29.                 }  
  30.   
  31.             }  
  32.     }  
  33.   
  34.     public static void bindColumnComment(XProperty property, Ejb3Column column) {  
  35.         if (null != column)  
  36.             if (property.isAnnotationPresent(Comment.class)) {  
  37.                 String comment = property.getAnnotation(Comment.class).value();  
  38.   
  39.                 column.getMappingColumn().setComment(comment);  
  40.   
  41.             }  
  42.     }  
  43. }  
  1. /** 
  2.  * $Id:$ 
  3.  */  
  4. package com.share.utils.hibernate;  
  5.   
  6. import org.hibernate.annotations.common.reflection.XClass;  
  7. import org.hibernate.annotations.common.reflection.XProperty;  
  8. import org.hibernate.cfg.Ejb3Column;  
  9. import org.hibernate.mapping.PersistentClass;  
  10.   
  11. import com.share.annotations.Comment;  
  12.   
  13. public class CommentBinder {  
  14.     public static void bindTableComment(XClass clazzToProcess, PersistentClass persistentClass) {  
  15.         if (clazzToProcess.isAnnotationPresent(Comment.class)) {  
  16.             String tableComment = clazzToProcess.getAnnotation(Comment.class).value();  
  17.             persistentClass.getTable().setComment(tableComment);  
  18.   
  19.         }  
  20.     }  
  21.   
  22.     public static void bindColumnComment(XProperty property, Ejb3Column[] columns) {  
  23.         if (null != columns)  
  24.   
  25.             if (property.isAnnotationPresent(Comment.class)) {  
  26.                 String comment = property.getAnnotation(Comment.class).value();  
  27.                 for (Ejb3Column column : columns) {  
  28.                     column.getMappingColumn().setComment(comment);  
  29.                 }  
  30.   
  31.             }  
  32.     }  
  33.   
  34.     public static void bindColumnComment(XProperty property, Ejb3Column column) {  
  35.         if (null != column)  
  36.             if (property.isAnnotationPresent(Comment.class)) {  
  37.                 String comment = property.getAnnotation(Comment.class).value();  
  38.   
  39.                 column.getMappingColumn().setComment(comment);  
  40.   
  41.             }  
  42.     }  
  43. }  
  1. /** 
  2.  * $Id:$ 
  3.  */  
  4. package com.share.annotations;  
  5.   
  6. import java.lang.annotation.ElementType;  
  7. import java.lang.annotation.Retention;  
  8. import java.lang.annotation.RetentionPolicy;  
  9. import java.lang.annotation.Target;  
  10.   
  11. @Target({ElementType.TYPE,ElementType.FIELD})  
  12. @Retention(RetentionPolicy.RUNTIME)  
  13. public @interface Comment {  
  14.     String value() default "";  
  15. }  
  1. /** 
  2.  * $Id:$ 
  3.  */  
  4. package com.share.annotations;  
  5.   
  6. import java.lang.annotation.ElementType;  
  7. import java.lang.annotation.Retention;  
  8. import java.lang.annotation.RetentionPolicy;  
  9. import java.lang.annotation.Target;  
  10.   
  11. @Target({ElementType.TYPE,ElementType.FIELD})  
  12. @Retention(RetentionPolicy.RUNTIME)  
  13. public @interface Comment {  
  14.     String value() default "";  
  15. }  

本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
Mybatis熱加載Mapper.xml
AnnotationHelloController.java
springmvc全局異常攔截處理
Spring boot(二)
hibernate在spring中的使用
基于全注解方式的SSH基礎(chǔ)框架(自認(rèn)為拿得出手,歡迎拍磚,歡迎繼續(xù)完善)
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服