English 中文(简体)
Null Pointer Exception when using DAO category
原标题:NullPointerException when using DAO class
  • 时间:2011-10-23 02:23:50
  •  标签:
  • java

I tried out DAO Pattern after reading http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html but I get NullPointerException when I run the servlet

<>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;

http://www.ohchr.org。

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();
    }
}
最佳回答

Stack trace points to MySQLUserDAO class and line s = conn.createStatement()

因此,<条码>conn 。

请看你如何重新建立<条码>conn:

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

因此,你无视所放弃的任何例外,并退回了<条码>null<>/code>链接,而不是放弃一个例外,以便守则立即停止。

你的技术问题是,司机显然没有上班,而你的真正设计问题是,除非你再次保证继续守则流通是安全的,否则你永远不应忽视例外情况。

以不必装载司机的方式装载everytime。 只是一次装上分类。

重述如下:

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");
}
问题回答

你可以尝试这种工厂。

<><>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);
 }

} 

Then you can call this factory from your ServiceEntitiesImpl (service implementantion).

public class ServiceEntityImp implements ServiceEntity {

    MySqlDAOFactory f;
    EntityDAOImp edi;

    public ServiceEntityImp() {

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

    }

最后,贵格会:

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;
    }


我的问题与这个问题一样,因此,我刚刚在我的网络内容领域失踪了我的q-连接。 因此,这需要在两个地点提及......





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签