Hibernate多对一关系映射

来源:互联网 发布:贵金属模拟软件 编辑:程序博客网 时间:2024/05/27 18:17

12720171106


package com.tiger.main;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import com.tiger.bean.School;import com.tiger.bean.Student;/** * n - 1(many to one) * 多位学生属于共同的一所大学(many 指的是学生) * 一所大学包含多位学生(one 指的是学校) * @author tiger * @date 2017年11月6日 */public class Main_many_one {public static void main(String[] args) {Configuration cfg = new Configuration().configure("hibernate.cfg.xml");SessionFactory sf = cfg.buildSessionFactory();Session session = sf.openSession();Transaction tx = session.beginTransaction();//new 一座大学School school01 = new School();school01.setName("北理工");School school02 = new School();school02.setName("北师珠");//new 多位学生Student student01 = new Student();student01.setName("小明");student01.setSchool(school01);Student student02 = new Student();student02.setName("小红");student02.setSchool(school01);Student student03 = new Student();student03.setName("小黄");student03.setSchool(school02);Student student04 = new Student();student04.setName("小黑");student04.setSchool(school02);session.save(student01);session.save(student02);session.save(student03);session.save(student04);tx.commit();session.close();sf.close();}}                                                                                                                package com.tiger.bean;/** * n 学生有很多 * @author tiger * @date 2017年11月6日 */public class Student {private Integer id;private String name;private School school;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public School getSchool() {return school;}public void setSchool(School school) {this.school = school;}public Student() { }@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + ", school=" + school + "]";}}                                                                            package com.tiger.bean;/** * 1 * 一所学生被多位学生共享 * @author tiger * @date 2017年11月6日 */public class School {private Integer id;private String name;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public School() {super();}@Overridepublic String toString() {return "School [id=" + id + ", name=" + name + "]";}}org.hibernate.dialect.MySQL5InnoDBDialectcom.mysql.jdbc.Driverjdbc:mysql://localhost:3306/book_many_oneroot12345630105000createtrue

阅读全文
1 0