jb下开发struts+hibernate
jbuilder下开发struts+hibernate
一、用jbuilder建立一个struts项目(略)
二、使用Middlegen生成需要的*.hbm.xml文件,并拷贝到src目录下,同时在jb中将xml文件定义为copy
1、确保需要的数据库驱动存在于lib目录下
2、在config\database目录下配置相应的数据库配置文件
3、修改build.xml文件
]>
4、使用ant编译运行
5、手动修改生成的文件
三、将需要的jar包导入项目(hibernate、dbdriver)
四、编写hibernate.cfg.xml,置于src目录下
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
(所有的*.hbm.xml文件都添加到这里)
五、编写HibernatePlugIn.java文件
import org.apache.struts.action.PlugIn;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.config.ModuleConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
public class HibernatePlugIn
implements PlugIn {
public void destroy() {
}
public void init(ActionServlet servlet, ModuleConfig config) throws
ServletException {
try {
ServletContext context = servlet.getServletContext();
SessionFactory sf = new Configuration().configure().buildSessionFactory();
context.setAttribute("net.sf.hibernate.SessionFactory",sf);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
六、修改struts-config.xml文件,加入plugin
七、使用hibernate
Context ctx = new InitialContext();
SessionFactory sf = (SessionFactory) ctx.lookup("hibernate/session_factory");
Session s = sf.openSession();
……
注:这部分可以抽象出来

Leave a comment