一个班级对应多个学生,学生中加入班级的引用,并用Many2One标注关联关系即可。
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
classes类正常映射即可,不用添加student类的引用。
student类需要添加clasess的引用,并且在classes的getter前添加Many2One。
@ManyToOne(fetch = FetchType.LAZY,cascade=CascadeType.ALL)
@JoinColumn(name = “classId”)
public Classes getClasses() {
return this.classes;
}
public void setClasses(Classes classes) {
this.classes = classes;
}
3.测试
package test1.model;
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”,cl1);
Student stu2 = new Student(“stu2”,cl1);
session.save(stu1);
session.save(stu2);
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
} finally {
session.close();
sessionFactory.close();
}
System.out.println(“事务结束”);
}
}