简体   繁体   English

hibernate如何使用no-arg构造函数初始化final字段?

[英]How hibernate is initializing final fields using the no-arg constructor?

So, I have this class which I am trying to use with Hibernate: 所以,我有这个类,我试图与Hibernate一起使用:

@Entity
@Access(AccessType.FIELD)
public class BasicUser {

    @Id 
    private final int userId;
    private final String userName;

    BasicUser(int userId, String userName) {
        super();
        this.userId = userId;
        this.userName = userName;
    }


    BasicUser() {
        super();
        this.userId=0;
        this.userName=null;
    }
    //getters

}

I tried pulling userId and userName from the database and make a BasicUser object and it worked fine. 我尝试从数据库中提取userId和userName并生成一个BasicUser对象,它工作正常。 But, I am not getting how did it work? 但是,我没有得到它是如何工作的? Hibernate required a no-arg constructor which I provided. Hibernate需要一个我提供的无参数构造函数。 Now since the fields are final, they had to be initialized in the constructor, so for sake of it I initialized them as shown in the code, expecting some error while running the code. 现在因为字段是final,所以它们必须在构造函数中初始化,所以为了它,我按照代码中所示初始化它们,期望在运行代码时出现一些错误。 But Hibernate formed the object with the field values as they were in the database. 但是Hibernate用数据库中的字段值形成了对象。 How is this happening? 这是怎么回事? I need to understand because, there are a few objects in my application which are immutable. 我需要理解,因为我的应用程序中有一些对象是不可变的。 So, should I be doing the same way for them also? 那么,我也应该为他们做同样的事情吗? I saw a lot of posts telling to provide a no-arg constructor and Access type as field for immutable objects. 我看到很多帖子告诉他们提供一个无参数构造函数和Access类型作为不可变对象的字段。 But, when I provide no-arg constructor for a final field, the field has to be initialized. 但是,当我为final字段提供no-arg构造函数时,必须初始化该字段。 So, I am not getting whats going on here? 所以,我不知道怎么回事? Please help. 请帮忙。 Thanks! 谢谢!

Hibernate uses reflection (or some related low-level trickery) to set private instance fields. Hibernate使用反射(或一些相关的低级技巧)来设置私有实例字段。 That approach can also by-pass final (ie reassign new values after the constructor returns). 该方法也可以绕过final (即在构造函数返回后重新分配新值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM