Juber Ahemad
Juber Ahemad

Reputation: 3

I am trying to mapping three entity with another entity by using onetoone annotation

I have three entity employee , info, and address , i want mapped employee entity with info and address entity by using onetoone mapping by using hibernate and jpa annotation.

@Entity
public class Employee {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private  int empId;
    private String name;
    private String email;
    
    @OneToOne(mappedBy = "emp", cascade = CascadeType.ALL)
    private Info info;
    
    @OneToOne(mappedBy = "emp", cascade = CascadeType.ALL)
    private Address address;
//getter and setter


@Entity
public class Info {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private  int infoId;
    private String gender;
    private String phone;
    
    @OneToOne
    @JoinColumn(name = "emp_id")
    private Employee emp;

//getter and setter

@Entity
public class Address {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private  int addrId;
    private String street;
    private String city;
    private String country;
    
    @OneToOne
    @JoinColumn(name = "emp_id")
    private Employee emp;
//getter and setter

public class OneToOneApp {

    public static void main(String[] args) {
        
        Configuration configuration = new Configuration();
        configuration.configure("o2omapping.cfg.xml");
        SessionFactory sessionFactory=configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
         
        Employee employee =new Employee();
        employee.setName("Iqra");
        employee.setEmail("[email protected]");
            
        Address address = new Address();
        address.setStreet("Manda Road");
        address.setCity("Allahabad");
        address.setCountry("India");
        
        Info info = new Info();
        info.setGender("FeMale");
        info.setPhone("12334567");
        
        employee.setInfo(info);
        info.setEmp(employee);
        address.setEmp(employee);
        
        session.save(employee);
        transaction.commit();
        session.close();
    }
}

alter table Info add constraint FKdjqy16j48ffa2x19eqgx3o8f0 foreign key (emp_id) references Employee (empId) Hibernate: insert into Employee (email, name) values (?, ?) Hibernate: insert into Info (emp_id, gender, phone) values (?, ?, ?)

data not Inserted into address table why??

Upvotes: 0

Views: 38

Answers (1)

emreozll
emreozll

Reputation: 16

he is telling the truth. You have set the address object in the customer class with a One-to-One relationship dependency, but you have not set its information. You should add this after the line employee.setAddress(), employee.setInfo().

Upvotes: 0

Related Questions