David Johnson
David Johnson

Reputation: 21

Hibernate Join Table issue

table: emps
(
  id int primary key,
  name varchar(50)
);

table: emps_sal
(
   emps_sal_id int primary key auto_increment,
   ids int,
   salary int,
   foreign key(ids) references emps(id)
);

Entity Classes:

@Entity
public class Emps {
    
    @Id
    @Column(name="id")
    int id;
    
    String name;
    
    @OneToOne(mappedBy = "e")
    Emps_sal esal;
--
}

@Entity
public class Emps_sal {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    int emps_sal_id;
    
    
    int  ids ;
    int salary;
    
    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn(name="ids")
    Emps e;
--
}

Now when I am doing simple select query its working fine. But when I am trying to add entry its working weirdly:

 Emps e=new Emps();
    e.setId(100);
    e.setName("Johnson");
    Emps_sal es=new Emps_sal();
    es.setIds(100);
    es.setSalary(5000);
    es.setE(e);
    e.setEsal(es);

Firstly in "emps" table it added a extra column "esal_emps_sal_id". Though it added "100,Johnson" properly. But in Emps_sal nothing is added. I was expecting "7, 100, 5000".

Upvotes: 0

Views: 32

Answers (1)

Doctor Who
Doctor Who

Reputation: 792

Change CascadeType to persist in Emps_sal entity class

@OneToOne(cascade = CascadeType.PERSIST)
    @PrimaryKeyJoinColumn(name="ids")
    Emps e;

The persist operation makes a transient instance persistent. CascadeType PERSIST propagates the persist operation from a parent to a child entity. When we save the Emps_sal entity, the Emp entity will also get saved.

Here is how you need to set the data

Emps e=new Emps();
        e.setId(100);
        e.setName("Johnson");
        Emps_sal es=new Emps_sal();
        es.setIds(100);
        es.setSalary(5000);
        es.setE(e);
        entityManager.persist(es);

Upvotes: 1

Related Questions