有一个f()函数,在其他类的main()函数里调用它就会持久化某一持久化类的一个属性,但是在servlet的doPost()函数中调用f()函数却不会持久化那个属性。
这是什么原因呢?
如何在servlet中持久化那个属性呢?
谢谢!!!

解决方案 »

  1.   

    Costomer类
    package hiber;
    import java.io.Serializable;
    import java.sql.Date;
    import java.sql.Timestamp;
    import java.util.*;public class Customer implements Serializable
    {
      int id;
      String nm;
      public Customer(){}
      
      public int getId(){ return it;}
      public void setId(int idd){this.it = idd;}  public String getNm(){return nm;}
      public void setNm(String name){this.nm=name;}
    }
    //////////////////////////////////////////////////////////////////////////
    BusinessService类
    package hiber;
    import org.hibernate.*;
    import org.hibernate.cfg.Configuration;
    import javax.servlet.*;
    import java.io.*;
    import java.util.*;
    public class BusinessService {
     public static SessionFactory sessionFactory;
      public BusinessService(){ }
     
     static{
        try{
          Configuration config = new Configuration();
          config.addClass(hiber.Customer.class);
          config.addClass(hiber.Order.class);
          sessionFactory = config.buildSessionFactory();
        }catch(Exception e){e.printStackTrace();}
      }  public void saveCustomer(Customer customer) throws Exception{
        
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
          
          session.save(customer);
          tx.commit();    }catch (Exception e) {
          if (tx != null) {
          tx.rollback();
          }
          throw e;
        } finally {
          session.close();
        }
      } 
      
     public  void f(){Customer customer=new Customer();customer.setNm("kkkkk");saveCustomer(customer);}     public static void  main(String[]  args)throws Exception{
      
          BusinessService bb=new  BusinessService();
          bb.f();
      
      }}运行BusinessService类结果:"kkkkk"被持久化到数据库。如果其他类的main()函数有BusinessService bb=new  BusinessService();
    bb.f();"kkkkk"也会被持久化到数据库。//////////////////////////////////////////////////////////////////////////////////////////////////////////
    Servlet类 DBServletpackage hiber;import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;public class DBServlet extends HttpServlet {  public void init(ServletConfig config)throws ServletException {super.init(config);}  public void doGet(HttpServletRequest request,HttpServletResponse response)
        throws ServletException, IOException {doPost(request, response);}  public void doPost(HttpServletRequest request,HttpServletResponse response)
        throws ServletException, IOException {
           try{
                 BusinessService bb=new  BusinessService();bb.f();
              }
          catch(Exception e){e.printStackTrace();}
                                             }  public void destroy() {}
    }服务器tomcat上运行DBServlet,"kkkkk"不会被持久化到数据库。