Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA OneToOne relationship

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:


User Object

@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;
}

UserSettings

@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?

like image 295
My Head Hurts Avatar asked Jul 21 '11 11:07

My Head Hurts


People also ask

What is difference between JPA unidirectional OneToOne and ManyToOne?

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.

How does JPA define one to one relationships?

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.

How does JPA handle one to many relationships?

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.


1 Answers

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".

like image 196
Ryan Stewart Avatar answered Sep 21 '22 21:09

Ryan Stewart