请教,泛型DAO调试不通,提示java.lang.NullPointerException。

刚刚接触学习泛型DAO,按照网上的一个例子来写,运行就提示,Exception in thread "main" java.lang.NullPointerException。开发环境是myeclipse6.5,jdk5.0,只好来这里请教,代码如下:

[code="java"]文件列表1:
文件名 说明
IDao.java dao的顶层抽象接口
AbstractDao.java IDao的实现类,实现了get/update/delete等基本操作
User.java USER表对应的entity定义
IUserDao.java USER表操作DAO接口定义
UserDao.java USER表操作DAO实现
HelloGenerics.java 测试类

IDao.java
// super dao interface
public interface IDao {
public T get(PK pk);
public List getAll();
public PK save(T entity);
public void update(T entity);
public void saveOrUpdate(T entity);
public void delete(T entity);
}

AbstractDao.java
//super abstract dao class
public abstract class AbstractDao implements IDao {
private Class clz;

public AbstractDao(Class clz) {
     this.clz = clz;
 }

public T get(PK pk) {
    return (T)getSession().get(clz, pk);
 }
public List <T>getAll() {
    return getSession().createCriteria(clz).list();
 }
public PK save(T entity) {
    return (PK)getSession().save(entity);
 }
public void update(T entity) {
     getSession().update(entity);
 }
public void saveOrUpdate(T entity) {
     getSession().saveOrUpdate(entity);
 }
public void delete(T entity) {
     getSession().delete(entity);
 }

private Session session;
protected Session getSession() {
    //wrap session in a class such as HibernateUtils, then you can use   HibernateUtils.getCurrentSession() for getting a session.
    return session;
 }

}

User.java
//persist entity
public class User {
private String id;
private String name;

public String getId() {
    return id;
 }
public void setId(String id) {
     this.id = id;
 }
public String getName() {
    return name;
 }
public void setName(String name) {
     this.name = name;
 }

//... setter/getter HERE

}
IUserDao.java
//User Dao interface
public interface IUserDao extends IDao {
// all are empty
}

UserDao.java
//UserDao Implementation
public class UserDao extends AbstractDao implements IUserDao {
public UserDao() {
super(User.class);
}
// or use the following constructor
//public UserDao(Class type) {
// super(type);
//}
}

HelloGenerics.java
public class HelloGenerics {

public static void main(String[] args) {
     IUserDao userDao = new UserDao();
     User user = userDao.get("1");
    if (user != null) {
         System.out.println(user.getName());
     }

     List<User> userList = userDao.getAll();
    for (User u:userList) {
         System.out.println(user.getName());
     }
 }

}[/code]

查看全部
weixin_42315822
丶Mythos
2009/06/16 11:21
  • dao
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

0个回复