Ravi Sharma
Ravi Sharma

Reputation: 873

Insert data in two mapped tables in spring

I have 2 table user and userprofile mapped with each other.

In User.java getter method for userprofile is :

 @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
 public Userprofile getUserprofiles() {
    return this.userprofiles;
 }

and in Userprofile.java getter method for user is :

 @OneToOne(fetch = FetchType.LAZY)
 @JoinColumn(name = "UserID")
 public User getUser() {
    return this.user;
 }

In User.jsp commandName is "userprofile", and submit method in controller is :

 @RequestMapping("/insertUser.do")
 public ModelAndView showLoginForm( @ModelAttribute("userprofile") Userprofile userProfileBean,BindingResult result, HttpServletRequest request, HttpServletResponse response )throws Exception
{

            java.util.Date utilDate=new java.util.Date();
            java.sql.Timestamp timest=new Timestamp(utilDate.getTime());

            userProfileBean.setEntryDate(timest);

            User user = new User();
            user.setUserProfile(userProfileBean);
            this.userServ.createUser(user);
            return new ModelAndView(new RedirectView("usersMapping.do"), "Test", "Test");

}

When i call the insert method of user class it is inserting into user as well as userprofile table but in the userprofile table userid is not updating.

Please help.

Upvotes: 2

Views: 1509

Answers (1)

Shahzad Badar
Shahzad Badar

Reputation: 114

You should add user Profile to user

user.setUserProfile(userProfileBean);

also add user object to userProfileBean

userProfileBean.setUser(user);

Upvotes: 1

Related Questions