Reputation: 5110
I have following entity class. I can put the annotations on top of the member variable declaration or on top of the getter and setter.
When I put annotation near member variable declaration, it will save the value of that variable(not the value returned by getter) and if I put annotation near getter, it will save value returned by getter(not value of variable). This is all fine.
My question is that while persisting, how hibernate able to access member variable value ,though it is declared a private, when we put annotation near member variable.?
@Entity
@Table(name="USERS")
public class Users {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
//This will save only value of userName no mater what getter returns
@Column(name="user_name")
private String userName;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
//Putting @Column(name="user_name") here will save value
// "userName from getter" to the DB
public String getUserName() {
return userName + " from getter";
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Upvotes: 2
Views: 315
Reputation: 61548
Hibernate and other JPA providers use reflection for private member access. In Java, like many OO languages, visibility declarations are not enforced so strictly that they cannot be bypassed
Upvotes: 1