一个班级对应多个学生,班级中加入学生集合的引用,并用One2Many标注关联关系即可。
1.见表
CREATE TABLE classes (
classId INT NOT NULL,
className VARCHAR(50),
CONSTRAINT `PRIMARY` PRIMARY KEY (classId)
);
CREATE TABLE student (
studentId INT NOT NULL,
classId INT,
studentName VARCHAR(50),
CONSTRAINT `PRIMARY` PRIMARY KEY (studentId),
CONSTRAINT student_ibfk_1 FOREIGN KEY (classId) REFERENCES classes(classId)
);
2.建model
student类正常映射即可,不用添加classes的引用。
classes类需要添加student的集合映射hashset,并且在此集合前添加One2Many。
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
//JoinColumn是为了避免创建中间表,默认系统会将One2Many视为Many2Many的特例而常见中间表
@JoinColumn(name = “classId”)
public Set<Student> getStudents() {
return this.students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
3.测试
package test1.model;
import java.util.HashSet;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateSample3 {
public static void main(String[] args) {
System.out.println(“开始事务”);
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
try {
Transaction tx = session.beginTransaction();
Classes cl1 = new Classes();
cl1.setClassName(“class1”);
Student stu1 = new Student(“stu1”);
Student stu2 = new Student(“stu2”);
HashSet hs1 = new HashSet();
hs1.add(stu1);
hs1.add(stu2);
cl1.setStudents(hs1);
session.save(cl1);
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
session.close();
sessionFactory.close();
}
System.out.println(“事务结束”);
}
}