JPA OneToOne Attitude

I am creating a project using the Play platform, and I'm having trouble lowering the JPA @OneToOne relationships .

I currently have two classes:


Custom 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'm trying to set the userId field inside User as a foreign key inside UserSettings . I tried several different ways to achieve this, and my code always throws an error. The most common error I get: A related property is not (one | many) ToOne .

However, when I try to set userId in UserSettings using the code above, I get the following exception:

Explicit exception javax.persistence.PersistenceException, org.hibernate.PropertyAccessException: could not get the field value by reflecting getter reader.User.id

Does anyone help explain how I can achieve my desired goal?

+4
source share
2 answers

Read section 5.2 of the sleep help for the difference between entities and values. You are trying to match String as an entity. Only entities can be (One | Many) ToOne, as the error tells you. Ie instead of String userId , you should use User user , and instead of mappedBy="userId" , mappedBy="user" .

+5
source

If you extend the model, Play will generate a default primary id key for each object. If this is not what you want, you should expand the overall model.

The easiest way is to provide the user as a property of user settings:

 @Entity @Table( name="user_settings" ) public class UserSettings extends Model{ @OneToOne public Users user; ... 
 @Entity @Table( name="users" ) public class Users extends Model { @OneToOne(cascade = CascadeType.ALL) public UserSettings settings; 

Maintaining user and user preferences in each facility using OneToOne enables bidirectional searches.
If you want to use your own key change from the model in GenericModel and define your foreign key on the user object.

0
source

All Articles