Play Framework, OneToOne relationship not working
I used both your models as you posted in the above link and tested successfully. As @Andrei mentioned in his comment the problem is not in mapping, it should be the way you saving them. Following are the code snippets i used for testing.
User
@Entitypublic class User extends Model{ / ..... fields as it is in your post public User(String user_id){ this.userId = user_id; } public static Finder<Long, User> find = new Finder<Long, User>(Long.class, User.class) public static User findByUserID(String user_id){ /* Your models already in bi-directional relationship, so there is no need for external `fetch`, You can directly get `UserLegalName` object from `User` model if there is any match found on `UserLegalName` for the input. */ return find.where().eq("userId",user_id).findUnique(); }}
UserLegalName
@Entitypublic class UserLegalName extends Model { / ..... fields as it is in your post public UserLegalName(User user_id, String first_name, String last_name){ this.user = user_id; this.firstName = first_name; this.lastName = last_name; }}
Controller
public class TestController extends Controller { public static Result insertUser(String user_id, String fname, String lname) { User user = new User(user_id); UserLegalName legal = new UserLegalName(user,fname,lname); user.legalName = legal; user.save(); return ok(user.legalName.firstName); } public static Result getUser(String user_id) { User user = User.findByUserID(user_id); return ok(user.legalName.firstName); }}
Routes
GET /test/:userID/:fname/:lname controllers.TestController.insertUser(userID : String, fname : String, lname : String)GET /user/:userID controllers.TestController.getUser(userID : String)
I suppose you set only one side of the relationship, and not both. As you have a bidirectional relationship you should set them both before persisting/merging, like:
userLegalName.setUser(user);user.setUserLegalName(userLegalName);entityManager.persist(userLegalName);entityManager.persist(user);