java


Hibernate session.createQuery().getResultList() returns null


I am struggling with null pointer, strange thing is that without relationship mapping it worked, but after I added mapping(many-to-one, one-to-many) it fails to retrieve result from DB (meaning List stays null)
Heres the code
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;
}
}
entity class
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;
}
}
and error
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)

Related Links

How to mainain log file in java
Google Calendar API android create event
Vertx HttpClient getNow not working
How to check the condition, whether the checkbox is clicked or not using java with selenium
How to call a method in same class from inside oncreate method android?
Getting an Error while locating an element using xpath in Selenium 3
Maven Dependency with type tag cannot be imported
Get Stream io Not able to update feed activities
Regarding the synchronized function
How to import an image and make a title at a check box in Java?
Why mockStatic doesn't behave as expected?
When creating object from classes that extend other classes [duplicate]
How to prevent LinkedHashMap from replacing Key/Value?
java.lang.OutOfMemoryError: GC overhead limit exceeded while Reading a Large Text file
How to read a BufferedReader without clearing it
Linkage error while deploying Axis 1 on wildfly 10

Categories

HOME
yii2
jdo
push-notification
include
grep
octobercms
jsrender
jgroups
jpeg
callback
blueprintjs
append
gitpitch
python-unittest
kibana-4
fancybox-3
modx-revolution
quickbooks
dtrace
iolanguage
highlight.js
fatal-error
finite-automata
jsdoc
custom-wordpress-pages
functional-testing
microsoft-r
blazemeter
h2db
vlsi
windows-server-2000
gitignore
file-rename
frame
key-value-observing
repo
language-concepts
cloud-code
environment-modules
mapdb
lto
unspecified
impersonation
botbuilder
ibpy
no-www
executenonquery
prolog-setof
boost-multi-index
dandelion
brightcove
slickedit
typed-lambda-calculus
np-complete
capacity
mcafee
iso8601
redundancy
specrun
pycaffe
instant
dstu2-fhir
persist
livequery
maven-tomcat-plugin
jqgrid-formatter
kcachegrind
cakephp-3.1
notify
geonetwork
nsmutabledictionary
camanjs
gui-test-framework
android-imagebutton
bitcoinj
system.net.webexception
aqtime
google-cloud-save
interface-orientation
selected
path-separator
isnullorempty
multipage
osql
ohm
qt-jambi
joyent
javax.script
propagation
mongomapper
lpeg
cxxtest
sudzc
gallio
xsdobjectgen
virtual-functions
nerddinner

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App