LaVOZs

The World’s Largest Online Community for Developers

'; Hibernate- OneToMany Relationship - LavOzs.Com

@Entity

@Table(name= "employee1100")

public class Employee {  

@Id

@Column(name="eid")

@GeneratedValue(strategy=GenerationType.AUTO)

private int id;  

@Column(name="ename")

private String name;

@OneToMany(mappedBy="employee",cascade=CascadeType.ALL)

private Set<Laptop> laptop;




@Entity

@Table(name="laptop1100")

public class Laptop {


    @Id

    @Column(name="laptop")

    @GeneratedValue(strategy=GenerationType.AUTO)

    private int id;

    @Column(name="lapdetails")

    private String details;

    @ManyToOne
    @JoinColumn(name="empId")
    private Employee employee;




    Laptop lap1=new Laptop();
    Laptop lap2=new Laptop();

    lap1.setDetails("Lenovo");
    lap2.setDetails("HP");

    Employee e1=new Employee(); 

    lap1.setEmployee(e1);
    lap2.setEmployee(e1);

    Set<Laptop> laptop=new HashSet<Laptop>();

    laptop.add(lap1);
    laptop.add(lap2);

    e1.setName("Rahul"); 
    e1.setLaptop(laptop);


    session.save(e1); 

I can see only one Laptop object inserted here respective to Employee record, Any issue?

Usually, when you use Set interface you should override the hashCode() and equals() methods. Have you tried List instead of Set interface?

Related
What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do
1:M relationship in Hibernate and cascading operations
Hibernate update table B after table A is updated
Hibernate unable to delete parent/child self-join entity
Hibernate: ManyToMany inverse Delete
Hibernate delete from onetomany
Fetch a children of a lazy one to many list
Hibernate : Why FetchType.LAZY-annotated collection property eagerly loading?
Hibernate deleted object would be re-saved by cascade
Right way to make insertion of an entity + foreign key on database(Use : Mysql, JPA)