说明:hibernate目前最高版本为3.6.0,struts的最高版本为2.2.1
在hibernate3.5版本以前,常用的包导入后,还需要:hibernate-commons-annotations.jar,hibernate-annotations.jar(反射时需要的包),ejb3-persistence.jar
而3.5及其以后的版本,需要导入:hibernate-jpa-2.0-api-1.0.0.Final.jar
目录结构:
Action中代码:
package com.xie.struts.action;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import com.opensymphony.xwork2.ActionSupport;
import com.xie.hibernate.modal.Student;
import com.xie.hibernate.modal.Teacher;
@SuppressWarnings("serial")
public class DbAction extends ActionSupport {
public String addStudent(){
Student s=new Student();
s.setId(6);
s.setName("cheng");
s.setAge(12);
Configuration cfg=new Configuration();
SessionFactory sf=cfg.configure().buildSessionFactory();
Session session=sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
System.out.println("ok");
return SUCCESS;
}
public String addTeacher(){
Teacher teacher=new Teacher();
teacher.setId(6);
teacher.setName("ma");
teacher.setAge(16);
teacher.setTitle("高级");
Configuration cfg=new AnnotationConfiguration();
SessionFactory sf=cfg.configure().buildSessionFactory();
Session session=sf.openSession();
session.beginTransaction();
session.save(teacher);
session.getTransaction().commit();
session.close();
System.out.println("ok");
return SUCCESS;
}
}