人与电话号码是一对多 ,多对一的关系
@Entity @Table(name="tb_person") public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; @OneToMany(mappedBy = "person") /*在双向一对多关系中 将控制权交给“多”方 */ private List<Telphone> telphoneList=new ArrayList<Telphone>(); public Person(String name) { this.name = name; } public Person() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Telphone> getTelphoneList() { return telphoneList; } public void setTelphoneList(List<Telphone> telphoneList) { this.telphoneList = telphoneList; } }
@Entity @Table(name="tb_telphone") public class Telphone { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String number; @ManyToOne //在多方配置级联 @Cascade(value = org.hibernate.annotations.CascadeType.SAVE_UPDATE) @JoinColumn(name="person_id") private Person person; public Telphone() { } public Telphone(String number) { this.number = number; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } }
public static void doublemanyToOneTest() { Person p1=new Person("一号"); Telphone t1=new Telphone("123456789"); Telphone t2=new Telphone("987654321"); p1.getTelphoneList().add(t1); p1.getTelphoneList().add(t2); t1.setPerson(p1); t2.setPerson(p1); Session session= Hibernate.getSession(); session.beginTransaction(); session.save(t1); session.save(t2); session.getTransaction().commit(); Hibernate.closeSession(session); }
时间: 2024-10-23 20:57:09