有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hibernate和noarg构造函数

正如我们所看到的hereHibenate不需要所有@Entity类的arg构造函数。但java类总是隐式地使用默认构造函数,即使我们没有显式地声明默认构造函数,这难道不是真的吗

在我的项目中,我没有在我的@Entity类中声明一个无参数构造函数,而且一切都正常。但另一方面,我想Hibernate规范编写得很仔细,所以实际上明确声明默认构造函数可能有一些好处


共 (6) 个答案

  1. # 1 楼答案

    显式地为实体类定义无参数构造函数没有什么特别的好处(但是请记住,Hibernate框架在内部使用无参数构造函数通过Java反射API填充实体)

    Hibernate实体Bean类必须不需要arg构造函数,而arg构造函数可以由程序员显式定义(或由Java自动生成)

    重要的一点是,当您为类定义自己的构造函数时,您需要自己提供无参数构造函数(因为在这种情况下编译器不提供)

  2. # 2 楼答案

    Java类可能没有隐式默认构造函数。 假设您有这样一个类:

    public class A {
        public A(String st) {}
    }
    

    最终,唯一的构造函数将是A(String st),而不是A(String st)和A()

  3. # 3 楼答案

    在Hibernate中,没有arg构造函数用于通过反射(用于在运行时检查或修改应用程序行为)加载数据库实体

  4. # 4 楼答案

    即使对于Hibernate,默认无参数构造函数的实现也不是强制性的,因为java会自动隐式地管理它

    唯一需要指定它的情况是在声明另一个参数化构造函数时

    如果您查看The No-Arg Constructor,您将看到:

    Every class has at least one constructor. There are two cases:

    1. If you do not write a constructor for a class, Java generates one for you. This generated constructor is called a default constructor. It's not visible in your code, but it's there just the same. If you could see it, it would look like this (for the class Dog): public Dog() { } Notice that this default constructor takes no arguments and has a body that does nothing.

    2. If you do write a constructor for your class, Java does not generate a default constructor. This could be a problem if you have pre-existing code that uses the default constructor.

  5. # 5 楼答案

    如果未定义任何构造函数,编译器将生成默认构造函数,如JLS中所述:

    If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

    If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

    这意味着您不必为Hibernate实体显式实现无参数构造函数,只要:

    1. 实体类中没有任何其他构造函数
    2. 扩展超类有一个无参数构造函数,对于任何已检查的异常都没有throws子句
  6. # 6 楼答案

    如果创建其他构造函数,java将不会创建隐式构造函数