Hibernate - 将注释从属性(方法)级别移动到字段级别

时间:2009-12-07 18:07:35

标签: reverse-engineering hibernate-annotations

如何从字段级别带注释的表生成hibernate域类?我使用了Hibernate Tools项目并从数据库中的表中生成了域类。生成的类在getter方法上有注释,而不是在字段级别。请建议一种方法来生成具有注释字段的域类。在eclipse / IDEA等中是否有任何重构工具可以将注释从方法级别移动到字段级别?

感谢您的帮助和时间。

3 个答案:

答案 0 :(得分:15)

以下是步骤:

  1. 通过在eclipse文件夹中执行搜索来分配“hibernate-tools.jar” 例如,你会发现它 C:\eclipse\plugins\org.hibernate.eclipse_3.4.1.xxx\lib\tools

  2. 提取到临时文件夹(WinRar可以这样做) 例如,提取到[Your Project]\template

  3. 在[Your Project] \ template \ pojo文件夹下,创建名为“Ejb3FieldGetAnnotation.ftl”的文件

    此文件实际上是“Ejb3PropertyGetAnnotation.ftl”的副本,但所有单词“property”都替换为“field”,因为此文件将放置在遍历所有字段(而不是属性)的循环中。 我在这篇文章中包含了文件的内容

  4. 删除属性级注释: 在文件“PojoPropertyAccessors.ftl”中,删除或注释掉

    <#include "GetPropertyAnnotation.ftl"/>
    
  5. 添加字段级注释: 在文件“PojoFields.ftl”中,添加

    <#include "Ejb3FieldGetAnnotation.ftl"/>
    ${pojo.getFieldModifiers(field)} ... 
    
  6. 生成Java实体时,选择“使用自定义模板”并指定模板文件夹。在这种情况下,它将是[Your Project] \ template

    ==================================================================================
    Ejb3FieldGetAnnotation.ftl
    ==================================================================================
    
    <#if ejb3>
    <#if pojo.hasIdentifierProperty()>
    <#if field.equals(clazz.identifierProperty)>
     ${pojo.generateAnnIdGenerator()}
    <#-- if this is the id property (getter)-->
    <#-- explicitly set the column name for this property-->
    </#if>
    </#if>
    
    <#if c2h.isOneToOne(field)>
    ${pojo.generateOneToOneAnnotation(field, cfg)}
    <#elseif c2h.isManyToOne(field)>
    ${pojo.generateManyToOneAnnotation(field)}
    <#--TODO support optional and targetEntity-->    
    ${pojo.generateJoinColumnsAnnotation(field, cfg)}
    <#elseif c2h.isCollection(field)>
    ${pojo.generateCollectionAnnotation(field, cfg)}
    <#else>
    ${pojo.generateBasicAnnotation(field)}
    ${pojo.generateAnnColumnAnnotation(field)}
    </#if>
    </#if>
    
  7. 希望它适合你。

答案 1 :(得分:1)

我花了很多时间阅读5年多以前的答案而不了解如何去做(特别是如果你在Intellij而不是Eclipse工作),为什么这还没有解决。所以我发现它,在这里,它很简单:

在Intellij:

  1. 使用此内容
  2. 在与orm.xml相同的文件夹中创建文件persistence.xml
    <?xml version="1.0" encoding="UTF-8"?>
        <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
                         version="2.0">
            <persistence-unit-metadata>
                <persistence-unit-defaults>
                    <access>FIELD</access>
                </persistence-unit-defaults>
            </persistence-unit-metadata>
        </entity-mappings>
    
    1. 现在你可以生成你的pojos(生成持久性映射 - &gt;按数据库模式 - &gt;选择你的表等,不要忘记勾选“Generate JPA Annotations”)
    2. 您的实体将有字段注释!

      @Entity
      @Table(name = "user", schema = "public", catalog = "my_db")
      public class User {
          @Id
          @Column(name = "id")
          private Integer id;
      ...
      }
      

答案 2 :(得分:0)

目前有必要使用自定义模板。这里有更多参考和示例热实现: https://forum.hibernate.org/viewtopic.php?f=6&t=1003858&p=2429868#p2429868