有一些基于序列化的技巧可以解决没有无参数构造函数的问题,因为序列化使用 jvm magic 在不调用构造函数的情况下创建对象。但这并不适用于所有虚拟机。例如,XStream可以创建没有公共非参数构造函数的对象实例,但只能通过在所谓的“增强”模式下运行,这种模式只能在某些 VM 上使用。(详情请参阅连结。)Hibernate 的设计人员肯定选择保持与所有 VM 的兼容性,因此避免了这种技巧,并使用官方支持的反射方法 Class<T>.newInstance(),该方法需要一个无参数构造函数。
I think that the proper way to do this would be to define in the Hibernate mapping how an object should be instantiated from the info in the database row using the proper constructor... but this would be more complex- meaning both Hibernate would be even more complex, the mapping would be more complex... and all to be more "pure"; and I don't think this would have an advantage over the current approach (other than feeling good about doing things "the proper way").
Many ORMs and serializers require parameterless constructors, because paramterized constructors through reflection are very fragile, and parameterless constructors provide both stability to the application and control over the object behavior to the developer.
Hibernate uses proxies for lazy loading. If you do no define a constructor or make it private a few things may still work - the ones that do not depend on proxy mechanism. For example, loading the object (with no constructor) directly using query API.
Hibernate 似乎对此有些不安全,因为在启动过程中,它会为我的每个实体类发出一条信息消息,告诉我 INFO: HHH000182: No default (no-argument) constructor for class和 class must be instantiated by Interceptor,但后来我确实用拦截器实例化了它们,它对此很满意。
Section 2.1 The Entity Class of the JPA 2.1 specification defines its requirements for an entity class. Applications that wish to remain portable across JPA providers should adhere to these requirements: