I tried to create one-to-one mapping using Hibernate. And when I am implementing the DAO method, I am getting the following error:
org.hibernate.AnnotationException: Unknown mappedBy in: com.User.userData, referenced property unknown: com.UserData.user
java.lang.NullPointerException
Why I am getting this error?
My codes are like the following:
For User entity code:
@Entity
@Table(name = "user")
public class User implements Serializable {
@Id
@GeneratedValue
@Column(name = "userid")
int userID;
@OneToOne(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
UserData userData;
...
}
For UserData entity code:
@Entity
@Table(name = "UserData")
public class UserData {
@Id
@GeneratedValue(generator = "generator")
@GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "user"))
int userID;
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
User user;
Change mappedBy=user
to mappedBy=userID
. That should solve your problem.
Although its odd that you are trying to do a bidirectional one to one, when this seems to only require a unidirectional. A bidirectional relationship implies that you can access your User object from inside your UserDetails object and vice versa, but I think you only need to access your UserDetails object from inside your User object, not the other way around.
Also, you don't need to specify FetchType.LAZY, that's the default option anyway.
If you want to change this to a unidirectional one to one, simply change your User class to:
@OneToOne
@PrimaryKeyJoinColumn
private UserData userData
and omit all reference to User inside your UserData class.
If this doesn't fix your problem, let me know
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.