I am building a project using the Play framework and I am having trouble getting my head around JPA @OneToOne relationships
.
I currently have two classes:
@Entity
@Table( name="users" )
public class Users extends Model {
@OneToOne( mappedBy="userId", fetch=FetchType.LAZY, cascade = CascadeType.ALL )
@ForeignKey( name="userId", inverseName="userId" )
UserSettings userSettings;
public userId;
public userName;
}
@Entity
@Table( name="user_settings" )
public class UserSettings extends Model {
@OneToOne( cascade = CascadeType.ALL,targetEntity=User.class )
public String userId;
public String xml;
public UserSettings( String userId ){
this.userId = userId;
}
}
The idea is that I am trying to set the userId
field within User
as a foreign key within UserSettings
. I have tried a few different ways to achieve this and my code always throws an error. The most common error I recveive is:
Referenced property not a (One|Many)ToOne.
However, When I try to set the userId
in UserSettings
using the code above, I receive the following exception:
A javax.persistence.PersistenceException has been caught, org.hibernate.PropertyAccessException: could not get a field value by reflection getter of reader.User.id
Can anybody help explain how I can achieve my desired goal?
The main difference between a OneToOne and a ManyToOne relationship in JPA is that a ManyToOne always contains a foreign key from the source object's table to the target object's table, whereas a OneToOne relationship the foreign key may either be in the source object's table or the target object's table.
For a One-to-One relationship in JPA, each entity instance is related to a single instance of another entity. It means each row of one entity is referred to one and only one row of another entity.
The One-To-Many mapping comes into the category of collection-valued association where an entity is associated with a collection of other entities. Hence, in this type of association the instance of one entity can be mapped with any number of instances of another entity.
Read section 5.2 of the hibernate reference about the difference between entities and values. You're trying to map a String as an entity. Only entities can be a (One|Many)ToOne, as the error is telling you. I.e., instead of String userId
, you should be using User user
, and instead of mappedBy="userId"
, mappedBy="user"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With