开发者

Can fields set by Hibernate be final?

My Eclipse does a number of code-cleaning actions automatically when I save a Java file, among them adding final to private fields where possible.

Will this conflict with Hibernate's ability to inject entity properties into private fields?

@Id
private final Long id = null;   // Eclipse made this "fi开发者_运维技巧nal"
                                // but Hibernate needs to set the id

Should I turn this save action off?

Update: I have tested the application and also looked at it with a debugger, and Hibernate does indeed reset the "final" field, so things continue to work okay. But is this guaranteed to work? For example, are there no VM or compiler optimizations that rely on a field really being final. Those would probably break. On the other hand, being able to set private fields via reflection seems to be a supported scenario, so the same thinking probably applies to final as well?


Even if it work, don't do it.

A final field can be written exactly once, and parts of the java memory model based on this fact.

I found this blog http://www.polygenelubricants.com/2010/03/modifying-static-final-fields-through.html which showed that it is possible to set an final via reflection with an real Hack. (But please don't do this in any real application.)

And this answer to an related question: Is there any way to declare final fields for Hibernate-managed objects?

In your case the simplest soultion would be: make the field mutable, and provied only a getter but not a setter.


hmm interesting question. I think on persisted objects you probably don't want to autoset final, for exactly the reason you mention.

It will definitely be a problem if your class has some sort of functionality where you do something like

setProperty(int prop) {
    this.prop = prop;
    fireChanged(); // updates other fields that depend on this one
}

which I have seen in a professional context. Although maybe here the plugin is smart enough to not make it final.

If you want to make your objects immutable, you could have your persistent class return an immutable subclass of itself, where the fields are private....

So there are advantages and disadvantages to that plugin. I guess you can do it either way, as long as you have tests to verify the auto-generated finals don't get in the way. Personally I would not use that plugin though -- I would look at the IDE warning and pick and choose my finals...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜