0
点赞
收藏
分享

微信扫一扫

Hibernate多对一关系映射


12720171106

Hibernate多对一关系映射_多对一


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() { }
@Override
public 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();
}
@Override
public String toString() {
return "School [id=" + id + ", name=" + name + "]";
}
}









org.hibernate.dialect.MySQL5InnoDBDialect





com.mysql.jdbc.Driver



jdbc:mysql://localhost:3306/book_many_one



root



123456






30



10



5000






create




true



举报

相关推荐

0 条评论