history中的c_id与s_id分别是外键。
在hibernate中用myeclicpse逆转工程实现的多对多
将 CourseDAO 中的save方法 改成:
public void save(Course transientInstance) {
log.debug("saving Course instance");
Session session=null;
Transaction tx=null;
try {
session=getSession();
tx=session.beginTransaction();
session.save(transientInstance);
tx.commit();
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
if(tx!=null){
tx.rollback();
}
throw re;
}
}
将 Student DAO 中的save方法 改成:
public void save(Student transientInstance) {
log.debug("saving Student instance");
Session session=null;
Transaction tx=null;
try {
session=getSession();
tx=session.beginTransaction();
session.save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
if(tx!=null){
tx.rollback();
}
throw re;
}
}
将 HistoryDAO 中的save方法 改成:
public void save(History transientInstance) {
log.debug("saving History instance");
Session session=null;
Transaction tx=null;
try {
session=getSession();
tx=session.beginTransaction();
session.save(transientInstance);
tx.commit();
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
if(tx!=null){
tx.rollback();
}
throw re;
}
}
测试类如下:
public class Test {
public static void main(String[] args) {
Course course=new Course();
CourseDAO cdao=new CourseDAO();
Student stu=new Student();
StudentDAO sdao=new StudentDAO();
History his=new History();
HistoryId hid=new HistoryId();
HistoryDAO hdao=new HistoryDAO();
course.setCName("c++");
course.setCTer("张三");
stu.setSName("张同学");
stu.setSAge(22);
hid.setCourse(course);
hid.setStudent(stu);
his.setId(hid);
cdao.save(course);
sdao.save(stu);
hdao.save(his);
}
}