user5871263
user5871263

Reputation:

To establish one to one relationship b/n entities in Spring and store the foreign key value

I have two tables as below in my mysql db:

CREATE TABLE if not exists USER (
      profile_id int(15) NOT NULL AUTO_INCREMENT,
      user_id varchar(30) NOT NULL,
      password varchar(30) NOT NULL,
      first_name varchar(50) NOT NULL,
      last_name varchar(50) NOT NULL,
      gender char(1) NOT NULL,
      nationality varchar(30) NOT NULL,
      date_of_birth date NOT NULL,
      place_of_birth varchar(30) DEFAULT NULL,
      notes tinytext,
      PRIMARY KEY (profile_id),
      KEY last_name_ind (last_name)
    ) ENGINE=InnoDB;

CREATE TABLE if not exists USER_CONTACT (
  contact_id int(5) NOT NULL AUTO_INCREMENT,
  profile_id int(15) NOT NULL,
  email_id varchar(30) NOT NULL,
  phone_no varchar(15) NOT NULL,
  address_current varchar(50) DEFAULT NULL,
  address_work varchar(50) DEFAULT NULL,
  address_permanent varchar(50) DEFAULT NULL,
  alternate_email varchar(30) DEFAULT NULL,
  alternate_phone varchar(30) DEFAULT NULL,
  PRIMARY KEY (contact_id),
  KEY A2B_USER_BASIC_FK (profile_id),
  CONSTRAINT A2B_USER_FK FOREIGN KEY (profile_id) REFERENCES a2b_user_basic (profile_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;

Then I want to save the user and user contact details together using JPA. The problem I am facing is storing the profile_id of table User to the second table USER_CONTACT as foreign key. This save should happen along with the user save.

Here are my entity classes.

User.java corresponds to the user table and I want to save the User using JPA. upon saving user contact entry.

    //User.java

    import java.util.Date;

    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.JoinColumn;
    import javax.persistence.OneToOne;
    import javax.persistence.Table;

    import org.hibernate.validator.constraints.NotEmpty;



    @Entity
    @Table(name="USER")
    public class User extends BaseEntity{

        @Column(name="profile_id")
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        protected Integer profileId;

        @Column(name="user_id")
        @NotEmpty
        protected String userId;

        @Column(name="password")
        protected String password;

        @Column(name="first_name")
        @NotEmpty
        protected String firstName;

        @Column(name="last_name")
        @NotEmpty
        protected String lastName;

        @Column(name="gender")
        @NotEmpty
        protected String gender;

        @Column(name="nationality")
        @NotEmpty
        protected String nationality;

        @Column(name="date_of_birth")
        protected Date dateOfBirth;

        @Column(name="place_of_birth")
        protected String placeOfBirth;

        @Column(name="notes")
        protected String notes;

        @OneToOne(mappedBy="user",fetch = FetchType.LAZY,cascade = CascadeType.ALL)
        @JoinColumn(name = "profile_id")
        protected UserContact userContact;

        public Integer getProfileId() {
            return profileId;
        }

        public void setProfileId(Integer profileId) {
            this.profileId = profileId;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public String getGender() {
            return gender;
        }

        public void setGender(String gender) {
            this.gender = gender;
        }

        public String getNationality() {
            return nationality;
        }

        public void setNationality(String nationality) {
            this.nationality = nationality;
        }

        public Date getDateOfBirth() {
            return dateOfBirth;
        }

        public void setDateOfBirth(Date dateOfBirth) {
            this.dateOfBirth = dateOfBirth;
        }

        public String getPlaceOfBirth() {
            return placeOfBirth;
        }

        public void setPlaceOfBirth(String placeOfBirth) {
            this.placeOfBirth = placeOfBirth;
        }

        public String getNotes() {
            return notes;
        }

        public void setNotes(String notes) {
            this.notes = notes;
        }


        public UserContact getUserContact() {
            return userContact;
        }

        public void setUserContact(UserContact userContact) {
            this.userContact = userContact;
        }



}

UserContact.java corresponds to the USER_CONTACT table and I want to establish a one to one relationship.

// UserContact.java

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.validator.constraints.NotEmpty;

import com.a2b.trackz.framework.model.BaseEntity;

@Entity
@Table(name="USER_CONTACT")
public class UserContact extends BaseEntity {

    @Column(name="contact_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Integer contactId;

    @Column(name="profile_id")
    protected Integer profileId;

    @Column(name="email_id")
    @NotEmpty
    protected String emailId;

    @Column(name="phone_no")
    @NotEmpty
    protected String phoneNo;

    @Column(name="address_current")
    protected String addressCurrent;

    @Column(name="address_work")
    protected String addressWork;

    @Column(name="address_permanent")
    protected String addressPermanent;

    @Column(name="alternate_email")
    protected String alternateEmail;

    @Column(name="alternate_phone")
    protected String alternatePhone;

    @OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
    protected User user;

    public Integer getContactId() {
        return contactId;
    }

    public void setContactId(Integer contactId) {
        this.contactId = contactId;
    }

    public Integer getProfileId() {
        return profileId;
    }

    public void setProfileId(Integer profileId) {
        this.profileId = profileId;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    public String getPhoneNo() {
        return phoneNo;
    }

    public void setPhoneNo(String phoneNo) {
        this.phoneNo = phoneNo;
    }

    public String getAddressCurrent() {
        return addressCurrent;
    }

    public void setAddressCurrent(String addressCurrent) {
        this.addressCurrent = addressCurrent;
    }

    public String getAddressWork() {
        return addressWork;
    }

    public void setAddressWork(String addressWork) {
        this.addressWork = addressWork;
    }

    public String getAddressPermanent() {
        return addressPermanent;
    }

    public void setAddressPermanent(String addressPermanent) {
        this.addressPermanent = addressPermanent;
    }

    public String getAlternateEmail() {
        return alternateEmail;
    }

    public void setAlternateEmail(String alternateEmail) {
        this.alternateEmail = alternateEmail;
    }

    public String getAlternatePhone() {
        return alternatePhone;
    }

    public void setAlternatePhone(String alternatePhone) {
        this.alternatePhone = alternatePhone;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
        this.profileId=user.getProfileId();
    }

}

Upvotes: 1

Views: 59

Answers (1)

arch
arch

Reputation: 1379

Change your entity classes reference like below:

User.Java

   @OneToOne(mappedBy="user",fetch = FetchType.LAZY,cascade = CascadeType.ALL)
   protected UserContact userContact;  

UserContact.java

 //remove this
        @Column(name="profile_id") 
        protected Integer profileId;    

       @OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
       protected User user;  

    //add this 
        @OneToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "profile_id", nullable = false)
        protected User user;

Upvotes: 1

Related Questions