0

I'm not familiar with Hibernate, and I saw this piece of code in a new project today:

public abstract class ValidationCode {

    @Column(name = "userId", updatable = false, insertable = false)
    @Getter
    @Setter
    private long userId;

    @ManyToOne
    @JoinColumn(name = "userId", referencedColumnName = "userId")
    @Getter
    @Setter
    private MasterUser user;

    // ....
}

My question is that is it redundant to declare userId field like this? Can we not just use a getter? Or maybe it values when in some cases like if we set the fetch type of user to be Lazy, we could access the userId field without fetching the user entity?

What would you suggest?

Yufeng Guo
  • 51
  • 4
  • In what way do you think the declaration of `userId` is redundant? Are you referring to the fact that there's a `@Column` annotation on the field `userId` rather than on the getter `getUserId()`? – Kevin Anderson Sep 17 '20 at 02:53
  • Seems duplicate of https://stackoverflow.com/questions/6311776/hibernate-foreign-keys-instead-of-entities – code_mechanic Sep 17 '20 at 03:13
  • @code_mechanic Thanks, I learnt a lot from the conversation from the post. Closing this as it's similar to the referenced one. – Yufeng Guo Sep 17 '20 at 03:32

1 Answers1

0

I think you are correct when you see this redundant. The @ManyToOne annotation specifies JoinColumn(name = "userId", ... which means the table where ValidationCode entity will be stored has a column userId that will be joined against the table where MasterUser is stored (and there, against a column named userId also). On the other hand the userId attribute is also mapped to a userId column on the table where ValidationCode is stored.

Now, honestly I don't know if this works. And if it does work what actually happens with those attributes. Also both have @Setter which makes things worse.

drkblog
  • 388
  • 2
  • 8
  • 1
    Yes, two `@Setter` thing is aweful. For some reason, once while updating such entity, I have to set new values for both `userId` and `user`, if only update the `user` entity, `userId` in the entity will not be updated. – Yufeng Guo Sep 17 '20 at 03:46