1、建立一个Class,HibernatePlugIn 放在src下
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
public class HibernatePlugIn implements PlugIn {
public void destroy() {
}
public void init(ActionServlet servlet, ModuleConfig config) throws ServletException {
try{
ServletContext context = null;
context = servlet.getServletContext();
SessionFactory sf = new Configuration().configure().
buildSessionFactory();
context.setAttribute("net.sf.hibernate.SessionFactory", sf);
}
catch(Exception e){
e.printStackTrace();
}
}
}
2、在struts-config.xml中添加
3、将hibernate.cfx.xml放在src目录下,并且属性设为copy
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
false
true
net.sf.hibernate.dialect.OracleDialect
oracle.jdbc.driver.OracleDriver
jdbc:oracle:thin:@192.168.100.242:1521:ecm
mydb_user
mydb_pass
20
hibernate/session_factory
这样以后就可以在任何地方调用了
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
public class HibernatePlugIn implements PlugIn {
public void destroy() {
}
public void init(ActionServlet servlet, ModuleConfig config) throws ServletException {
try{
ServletContext context = null;
context = servlet.getServletContext();
SessionFactory sf = new Configuration().configure().
buildSessionFactory();
context.setAttribute("net.sf.hibernate.SessionFactory", sf);
}
catch(Exception e){
e.printStackTrace();
}
}
}
2、在struts-config.xml中添加
3、将hibernate.cfx.xml放在src目录下,并且属性设为copy
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
false
true
net.sf.hibernate.dialect.OracleDialect
oracle.jdbc.driver.OracleDriver
jdbc:oracle:thin:@192.168.100.242:1521:ecm
mydb_user
mydb_pass
20
hibernate/session_factory
这样以后就可以在任何地方调用了
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
import javax.naming.InitialContext;
import javax.naming.Context;
public class MyService {
private SessionFactory sf;
public LoginService() throws Exception {
Context ctx = new InitialContext();
sf = (SessionFactory) ctx.lookup("hibernate/session_factory");
}
}