添加到HashSet时出现空指针异常

时间:2014-05-15 00:34:20

标签: java jpa nullpointerexception ejb hashset

即使我初始化了HashSet,当我尝试向其添加元素时,我得到一个空指针异常。

@OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, mappedBy = "artikal")
private Set<Cenovnik> cene = new HashSet<Cenovnik>();

public Set<Cenovnik> getCene() {
    if (cene == null)
        this.cene = new HashSet<Cenovnik>();

    return cene;
}

我这样用它:

Cenovnik cenovnik = new Cenovnik(date, null, cena);
Artikal artikal = artikalDao.findById(id);
Cenovnik stari = artikalDao.cena(id);

if (stari != null) {
    stari.setKrajkVazenja(date);
    cenovnikDao.merge(stari);
}

cenovnik.setArtikal(artikal);
artikal.getCene().add(cenovnik); //error!
cenovnikDao.persist(cenovnik);
artikalDao.merge(artikal);

因此,当我尝试将cenovnik添加到artikal.getCene时发生错误,我已经检查过,出于某种原因getCene似乎是问题所在。 这是Cenovnik类

public class Cenovnik implements Serializable{

/**
 * 
 */
private static final long serialVersionUID = -1436274372349853081L;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "cenovnik_id", unique = true, nullable = false)
private Integer id;
  ...   

@ManyToOne
@JoinColumn(name="artikal_id", referencedColumnName="artikal_id")
private Artikal artikal;    

public Artikal getArtikal() {
    return artikal;
}

public void setArtikal(Artikal artikal) {
    this.artikal = artikal;
}
    ...
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
}

} 这是完整的堆栈跟踪:

java.lang.NullPointerException:

        rs.ac.uns.acs.ism.server.servlet.DodajCenuArtiklaController.doGet(DodajCenuArtiklaController.java:78)

        rs.ac.uns.acs.ism.server.servlet.DodajCenuArtiklaController.doPost(DodajCenuArtiklaController.java:109)

        javax.servlet.http.HttpServlet.service(HttpServlet.java:641)

        javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

        org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)

        org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)

        org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)

        org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)

        org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)

        org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)

        rs.ac.uns.acs.ism.server.servlet.DodajArtikalController.doGet(DodajArtikalController.java:72)

        rs.ac.uns.acs.ism.server.servlet.DodajArtikalController.doPost(DodajArtikalController.java:94)

        javax.servlet.http.HttpServlet.service(HttpServlet.java:641)

        javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

        org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)

        org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)

        org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)

        org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)

        org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:45)

        org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)

        org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)

        org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)

        org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)

        org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)

        org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)

        org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)

        org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)

        org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)

        java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)

        java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)

        java.lang.Thread.run(Thread.java:745)

这里是等于方法:

    @Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Cenovnik other = (Cenovnik) obj;
    if (id == null) {
        if (other.id != null)
            return false;
    } else if (!id.equals(other.id))
        return false;
    return true;
}

2 个答案:

答案 0 :(得分:0)

您从数据源获取记录,然后使用它而不检查它是否为空。

尝试

Artikal artikal = artikalDao.findById(id);

if (artikal != null) {
   artikal.getCene().add(cenovnik);
}  else 
{
   // throw something
}

答案 1 :(得分:0)

如果artikal为null,则是一个单独的案例。然后像这样进行空检查

 if(artikal != null) {
    artikal.getCene().add(cenovnik);
 }

尝试这个调试分解getCene()并添加到两行并添加一些print语句,如果你使用的是一些logger使用它。这将有助于了解正在进行的工作

       if(artikal != null) {
            System.out.println("artikal is not null");
            Set<Cenovnik> cenovniks= artikal.getCene();

            if(cenovniks != null) {
                System.out.println("cenovniks set is not null");
                cenovniks.add(cenovnik);
                System.out.println("Added cenovnik to set");
            } else {
                // Handle null cenovniks as appropriate to your application
                System.out.println("cenovniks set is null");
            }
        } else {
            System.out.println("artikal is null");
            // Handle null artikal as appropriate to your application
        }

,否则

PLEAS注意这在添加到hashset时仅适用于hashset的add()方法

向对象添加对象的一个​​原因是抛出空指针异常是:

正在添加到hashset的对象的一个​​属性用于计算对象的哈希码。在计算hashcode期间,此属性抛出空指针异常。

它可以是日期或其他财产。检查类的hashcode实现在hashcode方法中放置一个断点,看看是否抛出了这个nullpointer。

更新1 查看hascode和equals方法似乎并没有导致问题。