Hibernate session.createQuery()。getResultList()返回null

时间:2017-01-16 14:03:12

标签: java hibernate orm nullpointerexception

我正在努力使用空指针,奇怪的是没有关系映射它起作用,但是在我添加映射(多对一,一对多)后,它无法从DB检索结果(意味着List保持为null )

继承代码

package entityfacade.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import entity.CategoryCompetenceEnumEntity;
import entity.CompetenceEntity;
import entity.impl.CompetenceEntityImpl;
import entityfacade.CategoryCompetenceEnumFacade;
import coma.entityfacade.CompetenceFacade;
import coma.objects.impl.FacadeGenerator;
import coma.objects.impl.FactoryGenerator;

public class CompetenceFacadeImpl implements CompetenceFacade {

/**
 * DONE
 */
FactoryGenerator fa = new FactoryGenerator();
SessionFactory factory = fa.getFactory();

@Override
public CompetenceEntity getCompetenceEntityByName(String name) {

    Transaction tx = null;
    Session session = factory.openSession();

    ArrayList<CompetenceEntity> entity = null;

    try {
        tx = session.beginTransaction();
        entity = (ArrayList<CompetenceEntity>) session
                .createQuery("FROM CompetenceEntityImpl C WHERE C.nameCompetence = " + name).getResultList();
        tx.commit();
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();

    } finally {
        session.close();

    }

    return entity.get(0);
}

/**
 * DONE
 */
@Override
public CompetenceEntity getCompetenceByIdCompetence(int id) {

    Transaction tx = null;
    Session session = factory.openSession();

    ArrayList<CompetenceEntity> entity = null;

    try {
        tx = session.beginTransaction();
        entity = (ArrayList<CompetenceEntity>) session
                .createQuery("FROM CompetenceEntityImpl C WHERE C.idCompetence = " + id).getResultList();
        tx.commit();
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();

    } finally {
        session.close();

    }

    return entity.get(0);
}

/**
 * DONE
 */
@Override
public List<CompetenceEntity> getAllCompetencies() {

    Transaction tx = null;
    SessionFactory factory = new Configuration().configure().buildSessionFactory();
    Session session = factory.openSession();

    List<CompetenceEntity> competencies = null;
    try {
        tx = session.beginTransaction();
        competencies = (List<CompetenceEntity>) session.createQuery("FROM CompetenceEntityImpl").getResultList();
        tx.commit();
        session.close();
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();

    } finally {
        factory.close();

    }

    if (competencies.size() < 1) {
        return null;
    }
    // Sort the criteria semi-lexicographically as defined in class
    // CompetenceComparator
    competencies.sort(new CompetenceComparator());
    return competencies;
}

/**
 * refactored DONE
 */
@Override
public boolean deleteCompetenceById(int id) {
    CompetenceEntity competence;

    try {
        competence = (CompetenceEntity) getCompetenceByIdCompetence(id);
    } catch (Exception e) {

        return false;
    }

    Transaction tx = null;
    Session session = factory.openSession();

    try {
        tx = session.beginTransaction();
        session.delete(competence);
        tx.commit();
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();

        return false;
    } finally {
        session.close();
    }
    return true;
}

/**
 * refactored DONE TODO Implement MySQL filter instead of Java filter
 */
@Override
public List<CompetenceEntity> getCompetenceByFilter(String filter) {
    List<CompetenceEntity> competenceEntityList = getAllCompetencies();
    List<CompetenceEntity> filteredList = new ArrayList<>();

    for (CompetenceEntity c : competenceEntityList) {
        if (c.getNameCompetence().contains(filter)) {
            filteredList.add(c);
        }
    }
    if (filteredList.size() < 1) {
        return null;
    }
    // Sort the criteria semi-lexicographically as defined in class
    // CompetenceComparator
    filteredList.sort(new CompetenceComparator());
    return filteredList;
}

/**
 * refactored
 * 
 */
@Override
public boolean insertCompetence(CompetenceEntity competenceEntity) {
    // Check if competence name is not empty
    if (competenceEntity.getNameCompetence().isEmpty()) {
        return false;
    }
    // check if competence name exists
    List<CompetenceEntity> competenceEntityList = getAllCompetencies();
    for (CompetenceEntity ce : competenceEntityList) {
        if (competenceEntity.getNameCompetence().equals(ce.getNameCompetence())) {
            return false;
        }
    }

    // check if categoryCompetenceEnum id is valid
    CategoryCompetenceEnumFacade catCompFacade = FacadeGenerator.generateCategoryCompetenceEnumFacade();
    List<Integer> enumIdList = new ArrayList<>();
    for (CategoryCompetenceEnumEntity ce : catCompFacade.getAllCategoryCompetencies()) {

        enumIdList.add(ce.getIdCategoryCompetenceEnum());
    }
    if (!enumIdList.contains(competenceEntity.getIdCategoryCompetenceEnum())) {
        return false;
    }

    Transaction tx = null;
    Session session = factory.openSession();

    try {
        tx = session.beginTransaction();
        CompetenceEntity competence = new CompetenceEntityImpl();
        competence.setNameCompetence(competenceEntity.getNameCompetence());
        competence.setIdCategoryCompetenceEnum(competenceEntity.getIdCategoryCompetenceEnum());
        session.save(competence);
        tx.commit();
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();

        return false;
    } finally {
        session.close();

    }
    return true;
}

}

/**
 * refactored DONE
 */
class CompetenceComparator implements Comparator<CompetenceEntity> {

@Override
public int compare(CompetenceEntity c1, CompetenceEntity c2) {
    // If c1 and c2 both start or both do not start with a
    // letter, return lexicographic comparison
    if (startsWithLetter(c1.getNameCompetence()) && startsWithLetter(c2.getNameCompetence())
            || !startsWithLetter(c1.getNameCompetence()) && !startsWithLetter(c2.getNameCompetence()))
        return c1.getNameCompetence().compareTo(c2.getNameCompetence());
    // If c1 does not start with a letter, but c2 does, return
    // -1
    if (!startsWithLetter(c1.getNameCompetence()) && startsWithLetter(c2.getNameCompetence()))
        return 1;
    // If c2 does not start with a letter, but c1 does, return
    // 1
    if (startsWithLetter(c1.getNameCompetence()) && !startsWithLetter(c2.getNameCompetence()))
        return -1;
    return 0;
}

/**
 * refactored DONE
 */
private boolean startsWithLetter(String str) {
    if (str.length() < 1)
        return false;
    char c = str.charAt(0);
    System.out.print("String = " + str + " c = " + c);
    if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
        System.out.println(" true");
        return true;
    }
    System.out.println(" false");
    return false;
}

}

实体类

package coma.entity.impl;

import java.io.Serializable;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import coma.entity.CriteriaEntity;
import coma.exception.InvalidIDException;

@Entity
@Table(name = "criteria")
public class CriteriaEntityImpl implements CriteriaEntity, Serializable {
/**
 * 
 */
private static final long serialVersionUID = 335515262135054142L;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "criteriaEntityImpl", targetEntity = CompetenceCriteriaEntityImpl.class)
public Set<CompetenceCriteriaEntityImpl> competenceCriteriaEntityImpl;
/**
 * 
 */

/**
 * Identifier of criteria
 */

/**
 * 
 */

/**
 * Identifier of criteria
 */
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id_criteria")
private int idCriteria;

public Set<CompetenceCriteriaEntityImpl> getCompetenceCriteriaEntityImpl() {
    return competenceCriteriaEntityImpl;
}

public void setCompetenceCriteriaEntityImpl(Set<CompetenceCriteriaEntityImpl> competenceCriteriaEntityImpl) {
    this.competenceCriteriaEntityImpl = competenceCriteriaEntityImpl;
}

public String getDescriptionCriteria() {
    return descriptionCriteria;
}

public void setDescriptionCriteria(String descriptionCriteria) {
    this.descriptionCriteria = descriptionCriteria;
}

public void setIdCriteria(int idCriteria) {
    this.idCriteria = idCriteria;
}

/**
 * Name of criteria
 */
@Column(name = "name_criteria")
private String nameCriteria;

/**
 * Identifier type criteria
 */
@Column(name = "id_name_type_criteria_enum")
private int idNameTypeCriteriaEnum;

/**
 * Description of criteria
 */
@Column(name = "description_criteria")
private String descriptionCriteria;

/**
 * Constructor without parameters
 */
public CriteriaEntityImpl() {

}

/**
 * Constructor with parameters
 * 
 * @param idCriteria
 * @param nameCriteria
 * @param idNameTypeCriteriaEnum
 * @param descriptionCriteria
 */
public CriteriaEntityImpl(int idCriteria, String nameCriteria, int idNameTypeCriteriaEnum,
        String descriptionCriteria) {
    this.idCriteria = idCriteria;
    this.nameCriteria = nameCriteria;
    this.idNameTypeCriteriaEnum = idNameTypeCriteriaEnum;
    this.descriptionCriteria = descriptionCriteria;
}

/**
 * Return identifier of current criteria
 * 
 * @return idCriteria
 */
@Override
public int getIdCriteria() {
    return idCriteria;
}

/**
 * Return name of current criteria
 * 
 * @return nameCriteria
 */
@Override
public String getNameCriteria() {
    return nameCriteria;
}

/**
 * Set name of current criteria
 * 
 * @param nameCriteria
 */
@Override
public void setNameCriteria(String nameCriteria) {
    this.nameCriteria = nameCriteria;
}

/**
 * Return identifier type criteria
 * 
 * @return idNameTypeCriteriaEnum
 */
@Override
public int getIdNameTypeCriteriaEnum() {
    return idNameTypeCriteriaEnum;
}

/**
 * Set identifier type criteria
 * 
 * @param idNameTypeCriteriaEnum
 */
@Override
public void setIdNameTypeCriteriaEnum(int idNameTypeCriteriaEnum) throws InvalidIDException {
    if (idNameTypeCriteriaEnum < 0) {
        throw new InvalidIDException("The idNameTypeCriteriaEnum must be greater than 0");
    } else {
        this.idNameTypeCriteriaEnum = idNameTypeCriteriaEnum;
    }

}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((descriptionCriteria == null) ? 0 : descriptionCriteria.hashCode());
    result = prime * result + idCriteria;
    result = prime * result + idNameTypeCriteriaEnum;
    result = prime * result + ((nameCriteria == null) ? 0 : nameCriteria.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    CriteriaEntityImpl other = (CriteriaEntityImpl) obj;
    if (descriptionCriteria == null) {
        if (other.descriptionCriteria != null)
            return false;
    } else if (!descriptionCriteria.equals(other.descriptionCriteria))
        return false;
    if (idCriteria != other.idCriteria)
        return false;
    if (idNameTypeCriteriaEnum != other.idNameTypeCriteriaEnum)
        return false;
    if (nameCriteria == null) {
        if (other.nameCriteria != null)
            return false;
    } else if (!nameCriteria.equals(other.nameCriteria))
        return false;
    return true;
}



}

和错误

SEVERE: Servlet.service() for servlet [Jersey RESTful Application] in context with path [/COMAService] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at coma.entityfacade.impl.CompetenceFacadeImpl.getAllCompetencies(CompetenceFacadeImpl.java:109)
    at coma.service.impl.CompetenceServiceImpl.postAll(CompetenceServiceImpl.java:86)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)

0 个答案:

没有答案