简体   繁体   中英

Hibernate- OneToMany Relationship

@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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM