生成的完整构造函数包含太多参数



我有一个DB表,其中有很多字段,当我使用Hibernate .hbm文件为该表生成POJO时,这会导致一个问题。问题是生成的完整构造函数为Java生成了太多的参数,这会抛出编译器错误:

参数太多,参数xxxx超过了方法参数255个字的限制

我想通过抑制Hibernate生成完整构造函数来解决这个问题。我的问题是

  1. 如果我没有完整的构造函数,Hibernate会在运行时中断吗?
  2. 我如何告诉我的hbm不生成完整的构造函数?

谢谢大家的回答。

使用Hibernate 3.6(可能也适用于早期版本,但我还没有测试过),您可以通过创建以下文件来定制Hibernate工具代码生成,如果构造函数有超过255个参数,则跳过创建构造函数:

$ {hibernate-cust-src}/pojo PojoConstructors.ftl

<#--  /** default constructor */ -->
    public ${pojo.getDeclarationName()}() {
    }
<#if pojo.needsMinimalConstructor() && pojo.getPropertiesForMinimalConstructor().size() lte 255>    <#-- /** minimal constructor */ -->
    public ${pojo.getDeclarationName()}(${c2j.asParameterList(pojo.getPropertyClosureForMinimalConstructor(), jdk5, pojo)}) {
<#if pojo.isSubclass() && !pojo.getPropertyClosureForSuperclassMinimalConstructor().isEmpty() >
        super(${c2j.asArgumentList(pojo.getPropertyClosureForSuperclassMinimalConstructor())});        
</#if>
<#foreach field in pojo.getPropertiesForMinimalConstructor()>
        this.${field.name} = ${field.name};
</#foreach>
    }
</#if>    
<#if pojo.needsFullConstructor() && pojo.getPropertiesForFullConstructor().size() lte 255>
<#-- /** full constructor */ -->
    public ${pojo.getDeclarationName()}(${c2j.asParameterList(pojo.getPropertyClosureForFullConstructor(), jdk5, pojo)}) {
<#if pojo.isSubclass() && !pojo.getPropertyClosureForSuperclassFullConstructor().isEmpty()>
        super(${c2j.asArgumentList(pojo.getPropertyClosureForSuperclassFullConstructor())});        
</#if>
<#foreach field in pojo.getPropertiesForFullConstructor()> 
       this.${field.name} = ${field.name};
</#foreach>
    }
</#if>  

覆盖PojoConstructors。hibernate-tools.jar.

如果使用Ant进行构建,则需要确保${hibernate-cust-src}位于hibernate-tools任务的类路径中。

<path id="toolslib">
    <pathelement location="${hibernate-cust-src}"/>
    ... [other locations for hibernate-tools and dependencies]
</path>
<taskdef name="hibernatetool" 
         classname="org.hibernate.tool.ant.HibernateToolTask" 
         classpathref="toolslib"/>

注意,这是一个bug在hibernate工具创建一个构造函数有>255个参数…

: Hibernate只需要一个空的私有构造函数

在Java中,你不能为一个方法或构造函数定义超过255个参数。这是Java中的限制。Hibernate也遵循同样的策略。

由于Hibernate总是使用默认构造函数,那么最好在PojoConstructors模板中删除完整的构造函数生成。

$ {hibernate-cust-src}/pojo PojoConstructors.ftl

<#--  /** default constructor */ -->
    public ${pojo.getDeclarationName()}() {
    }

最新更新