使用DAO类时出现NullPointerException

时间:2011-10-23 02:23:50

标签: java

我读完后尝试了DAO Pattern http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html 但是当我运行servlet

时,我得到NullPointerException

DAOFactory

package dao;
import java.sql.SQLException;
public abstract class DAOFactory {
// List of DAO types supported by the factory
public static final int MYSQL = 1;

public abstract UserDAO getUserDAO() throws SQLException;

public static DAOFactory getDAOFactory(int whichFactory) {

switch (whichFactory) {
  case MYSQL: 
      return new MySQLDAOFactory();
  default        : 
      return null;
}
}
}

MySQLDAOFactory

package dao;
import java.sql.*;
public class MySQLDAOFactory extends DAOFactory {

public MySQLDAOFactory() {
}
public static final String DRIVER="com.mysql.jdbc.Driver";
public static final String DBURL="jdbc:mysql://localhost:3306/musicompany";

public static Connection createConnection() {
    Connection conn=null;
    try{
        Class.forName(DRIVER);
        conn =  DriverManager.getConnection(DBURL,"root","toor");
    }catch(Exception e){}
    return conn;
}
public UserDAO getUserDAO() throws SQLException{
    return new MySQLUserDAO();
}
}

MySQLUserDAO

package dao;
import java.sql.*;
import java.util.ArrayList;
import model.User;

public class MySQLUserDAO implements UserDAO {

Connection conn=null;
Statement s=null;
public MySQLUserDAO() throws SQLException{
    conn = MySQLDAOFactory.createConnection();
    s = conn.createStatement();
}

public int insertUser(String fname, String lname) 
{
    try{
    //code to insertUser
    }catch(Exception e){}
    return key;
}


public ArrayList<User> selectUsers() {
    ResultSet rs=null;
    ArrayList customerList=null;
    try{
        rs =s.executeQuery("select * from users");
        customerList = new ArrayList<User>();
        while(rs.next())
        {
            customerList.add(new User(rs.getString("name"), rs.getString("pass"), rs.getInt("type"), rs.getString("email")));
        }
        return customerList;
    }catch(Exception e){}
    return customerList;
}
}

UserDAO的

package dao;
import java.util.ArrayList;
import model.User;

public interface UserDAO {
public int insertUser(String fname, String lname);
public ArrayList<User> selectUsers();
} 

model.User.java

该类具有以下字段和相应的访问器方法。

String name;
String pass;
short type;
String email;

我的Servlet文件

public class AddRetrieve extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        // create the required DAO Factory
        DAOFactory factoryObj = DAOFactory.getDAOFactory(DAOFactory.MYSQL);

        // Create a DAO
        UserDAO custDAO = factoryObj.getUserDAO();

        // print existing users
        ArrayList list = custDAO.selectUsers();
        Iterator i = list.iterator();
        while(i.hasNext())
        {
            User o = (User)i.next();
            out.println(o.getName());
        }

    } catch(Exception e)
    {
        out.println(e);
    }
    finally {            
        out.close();
    }
}

3 个答案:

答案 0 :(得分:2)

  

堆栈跟踪指向MySQLUserDAO类和行s = conn.createStatement()

因此,connnull

让我们来看看你是如何创建conn

public static Connection createConnection() {
    Connection conn=null;
    try{
        Class.forName(DRIVER);
        conn =  DriverManager.getConnection(DBURL,"root","toor");
    }catch(Exception e){}
    return conn;
}

因此,您忽略了抛出的任何异常并返回null连接而不是抛出异常,以便代码立即停止。

您的技术问题是由于驱动程序显然不属于类路径而您的实际设计问题是您永远不应忽略异常,除非您100%确定继续代码流是安全的。

这是不必每次都加载驱动程序的方式。只需在类初始化时加载一次。

重写该内容如下:

static {
    try{
        Class.forName(DRIVER);
    } catch (ClassNotFoundException e) {
        throw new ExceptionInInitializerError("Driver " + DRIVER + " missing in classpath", e);
    }
}

public static Connection createConnection() throws SQLException {
    return DriverManager.getConnection(DBURL, "root", "toor");
}

答案 1 :(得分:1)

您可以尝试使用这种工厂

MySqlDAOFactory

public class MySqlDAOFactory {
private EntityManagerFactory emf;
private EntityManager em;

private static MySqlDAOFactory f;

private MySqlDAOFactory() {

Persistence.generateSchema("#persistance-Unit#", null);
  emf = Persistence.createEntityManagerFactory("#persistance-Unit#");
  em = emf.createEntityManager();
 }

 public static MySqlDAOFactory getFactory() {
  if (f == null){
   f= new MySqlDAOFactory();
                }
  return f;
 }

 public EntityDAOA getEntityDAOA() {
  return new EntityDAOAImpl(em);
 }

 public EntityDAOB getEntityDAOB() {
  return new EntityDAOBImpl(em);
 }

} 

然后,您可以从ServiceEntitiesImpl(服务实现)调用此工厂。

public class ServiceEntityImp implements ServiceEntity {

    MySqlDAOFactory f;
    EntityDAOImp edi;

    public ServiceEntityImp() {

        f = MySqlDAOFactory.getFactory();
        edi = (EntityDAOImp) f.getEntityDAO();

    }

最后,您的DAO就像:

public class EntityDAOImp implements EntityDAO {

    EntityManager em;

    public EntityDAOImp(EntityManager em) {
        this.em = em;
    }

    public int insertEntity(EntityVO entity) {
        try {
            em.getTransaction().begin();
            em.persist(entity);
            em.getTransaction().commit();
            return 1;

        } catch (Exception e) {
            System.out.println("Error with entity insert "+e.getMessage());
        }
        return 0;
    }

public List<EntityVO> listEntity(String entityB) {

        List<EntityVO> listByEntityB = new ArrayList<EntityVO>();
        em.getTransaction().begin();
        Query query = em.createQuery(
                "select distinct t from EntityVO t join fetch t.entityB b where b.entityB.name = :entityB");
        query.setParameter("entityB", entityB);
        listByEntityB = query.getResultList();
        em.getTransaction().commit();
        return listByEntityB;
    }


答案 2 :(得分:0)

我遇到了同样的问题,事实证明我在网络内容区域中缺少mysql-connector jar。所以这需要在2个地方引用......