NullPointerException because of the same hibernate constructor - java

I am using hibernate 4.2.0. I am having the following class:
#Entity
public class TestData {
#Id
#GeneratedValue
private Long id;
private String customerNr;
private String FirstName;
private String LastName;
/**
*
*/
public TestData() {
super();
}
/**
* #param customerNr
*/
public TestData(String customerNr) {
super();
this.customerNr = customerNr;
}
/**
* #param id
* #param customerNr
* #param firstName
* #param lastName
*/
public TestData(Long id, String customerNr, String firstName,
String lastName) {
super();
this.id = id;
this.customerNr = customerNr;
FirstName = firstName;
LastName = lastName;
}
//getter and setter etc.
}
To get all customerNr I am using the following query:
#Transactional
#SuppressWarnings("all")
public List<TestData> getCustomerNrFilter(String customerNr) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<TestData> criteria = cb.createQuery(TestData.class);
//which table we want to fetch
final Root root = criteria.from(TestData.class);
//create statement
criteria.select(cb.construct(TestData.class, root.get("customerNr"))).distinct(true);
// Pass the criteria list to the where method of criteria query
criteria.where(cb.and((Predicate[]) criteriaList.toArray(new Predicate[0])));
// Order by clause
criteria.orderBy(cb.asc(root.get("customerNr")));
return em.createQuery(criteria).getResultList();
}
public List createWhereCritera(String customerNr, CriteriaBuilder cb,
final Root root) {
// This list will contain all Predicates (where clauses)
List criteriaList = new ArrayList();
// CustomerNr: where condition: TestData.CustomerNr like '%'
Predicate predicateFirstName = cb.like(cb.upper(root.get("customerNr")),customerNr);
criteriaList.add(predicateFirstName);
return criteriaList;
}
As I see the customerNr uses this constructor to get my data:
/**
* #param customerNr
*/
public TestData(String customerNr) {
super();
this.customerNr = customerNr;
}
However, using the same query for `firstName`:
#Transactional
#SuppressWarnings("all")
public List<TestData> getCustomerNrFilter(String firstName) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<TestData> criteria = cb.createQuery(TestData.class);
//which table we want to fetch
final Root root = criteria.from(TestData.class);
//create statement
criteria.select(cb.construct(TestData.class, root.get("firstName"))).distinct(true);
// Pass the criteria list to the where method of criteria query
criteria.where(cb.and((Predicate[]) criteriaList.toArray(new Predicate[0])));
// Order by clause
criteria.orderBy(cb.asc(root.get("firstName")));
return em.createQuery(criteria).getResultList();
}
public List createWhereCritera(String firstName, CriteriaBuilder cb,
final Root root) {
// This list will contain all Predicates (where clauses)
List criteriaList = new ArrayList();
// firstName: where condition: TestData.firstName like '%'
Predicate predicateFirstName = cb.like(cb.upper(root.get("firstName")),firstName);
criteriaList.add(predicateFirstName);
return criteriaList;
}
However, firstName also tries to use the customerNr constructor to get my data:
/**
* #param customerNr
*/
public TestData(String customerNr) {
super();
this.customerNr = customerNr;
}
Right now, giving the data back gives me a Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException, because only the customerNr is queried and not the firstName.
I cannot really create two constructors of the same type, because then I would have a duplicated method. Furthermore, leaving the constructor out gives me the exception no appropriate constructor
Any recommendations what I should do?
UPDATE 1
Commenting all constructors out gives me:
Unable to locate appropriate constructor on class [com.Application.domain.TestData] [select distinct new com.Application.domain.TestData(generatedAlias0.customerNr) from com.Application.domain.TestData as generatedAlias0 where ( upper(generatedAlias0.customerNr) like :param0 ) and ( upper(generatedAlias0.firstName) like :param1 ) ...
I appreciate your replies!
UPDATE 2
My whole stacktrace:
3408 [AWT-EventQueue-0] ERROR org.hibernate.hql.internal.ast.ErrorCounter - Unable to locate appropriate constructor on class [com.Application.domain.TestData]
[cause=org.hibernate.PropertyNotFoundException: no appropriate constructor in class: com.Application.domain.TestData]
3408 [AWT-EventQueue-0] ERROR org.hibernate.hql.internal.ast.ErrorCounter - Unable to locate appropriate constructor on class [com.Application.domain.TestData]
[cause=org.hibernate.PropertyNotFoundException: no appropriate constructor in class: com.Application.domain.TestData]
Unable to locate appropriate constructor on class [com.Application.domain.TestData]
[cause=org.hibernate.PropertyNotFoundException: no appropriate constructor in class: com.Application.domain.TestData]
at org.hibernate.hql.internal.ast.tree.ConstructorNode.resolveConstructor(ConstructorNode.java:187)
at org.hibernate.hql.internal.ast.tree.ConstructorNode.prepare(ConstructorNode.java:152)
at org.hibernate.hql.internal.ast.HqlSqlWalker.processConstructor(HqlSqlWalker.java:1019)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2279)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2145)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1451)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:571)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1777)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:452)
at org.hibernate.ejb.criteria.CriteriaQueryCompiler.compile(CriteriaQueryCompiler.java:221)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:587)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241)
at com.sun.proxy.$Proxy14.createQuery(Unknown Source)
at com.Application.dao.TestDaoImpl.getCustomerNrTest(TestDaoImpl.java:137)
at com.Application.dao.TestDaoImpl$$FastClassByCGLIB$$a62bf500.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
at com.Application.dao.TestDaoImpl$$EnhancerByCGLIB$$6ca0bd06.getCustomerNrTest(<generated>)
at com.Application.service.TestServiceImpl.getCustomerNrTest(TestServiceImpl.java:39)
at com.Application.gui.scenarioSelection.MainTabPanel.placeSelectionWithButtons(MainTabPanel.java:145)
at com.Application.gui.scenarioSelection.MainTabPanel.createLayout(MainTabPanel.java:119)
at com.Application.gui.scenarioSelection.MainWindow.createTabBar(MainWindow.java:132)
at com.Application.gui.scenarioSelection.MainWindow.makeLayout(MainWindow.java:182)
at com.Application.gui.scenarioSelection.MainWindow.access$1(MainWindow.java:172)
at com.Application.gui.scenarioSelection.MainWindow$4.run(MainWindow.java:197)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForTests(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForTest(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Cause:
org.hibernate.PropertyNotFoundException: no appropriate constructor in class: com.Application.domain.TestData
at org.hibernate.internal.util.ReflectHelper.getConstructor(ReflectHelper.java:372)
at org.hibernate.hql.internal.ast.tree.ConstructorNode.resolveConstructor(ConstructorNode.java:179)
at org.hibernate.hql.internal.ast.tree.ConstructorNode.prepare(ConstructorNode.java:152)
at org.hibernate.hql.internal.ast.HqlSqlWalker.processConstructor(HqlSqlWalker.java:1019)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2279)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2145)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1451)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:571)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1777)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:452)
at org.hibernate.ejb.criteria.CriteriaQueryCompiler.compile(CriteriaQueryCompiler.java:221)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:587)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241)
at com.sun.proxy.$Proxy14.createQuery(Unknown Source)
at com.Application.dao.TestDaoImpl.getCustomerNrTest(TestDaoImpl.java:137)
at com.Application.dao.TestDaoImpl$$FastClassByCGLIB$$a62bf500.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
at com.Application.dao.TestDaoImpl$$EnhancerByCGLIB$$6ca0bd06.getCustomerNrTest(<generated>)
at com.Application.service.TestServiceImpl.getCustomerNrTest(TestServiceImpl.java:39)
at com.Application.gui.scenarioSelection.MainTabPanel.placeSelectionWithButtons(MainTabPanel.java:145)
at com.Application.gui.scenarioSelection.MainTabPanel.createLayout(MainTabPanel.java:119)
at com.Application.gui.scenarioSelection.MainWindow.createTabBar(MainWindow.java:132)
at com.Application.gui.scenarioSelection.MainWindow.makeLayout(MainWindow.java:182)
at com.Application.gui.scenarioSelection.MainWindow.access$1(MainWindow.java:172)
at com.Application.gui.scenarioSelection.MainWindow$4.run(MainWindow.java:197)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForTests(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForTest(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [com.Application.domain.TestData] [select distinct new com.Application.domain.TestData(generatedAlias0.CustomerNr) from com.Application.domain.TestData as generatedAlias0 where ( upper(generatedAlias0.CustomerNr) like :param0 ) and ( upper(generatedAlias0.City) like :param1 ) and ( upper(generatedAlias0.Country) like :param2 ) and ( upper(generatedAlias0.UseType) like :param3 ) and ( upper(generatedAlias0.ProjStat) like :param4 ) order by generatedAlias0.CustomerNr asc]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1374)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:470)
at org.hibernate.ejb.criteria.CriteriaQueryCompiler.compile(CriteriaQueryCompiler.java:221)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:587)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241)
at com.sun.proxy.$Proxy14.createQuery(Unknown Source)
at com.Application.dao.TestDaoImpl.getCustomerNrTest(TestDaoImpl.java:137)
at com.Application.dao.TestDaoImpl$$FastClassByCGLIB$$a62bf500.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
at com.Application.dao.TestDaoImpl$$EnhancerByCGLIB$$6ca0bd06.getCustomerNrTest(<generated>)
at com.Application.service.TestServiceImpl.getCustomerNrTest(TestServiceImpl.java:39)
at com.Application.gui.scenarioSelection.MainTabPanel.placeSelectionWithButtons(MainTabPanel.java:145)
at com.Application.gui.scenarioSelection.MainTabPanel.createLayout(MainTabPanel.java:119)
at com.Application.gui.scenarioSelection.MainWindow.createTabBar(MainWindow.java:132)
at com.Application.gui.scenarioSelection.MainWindow.makeLayout(MainWindow.java:182)
at com.Application.gui.scenarioSelection.MainWindow.access$1(MainWindow.java:172)
at com.Application.gui.scenarioSelection.MainWindow$4.run(MainWindow.java:197)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForTests(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForTest(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [com.Application.domain.TestData] [select distinct new com.Application.domain.TestData(generatedAlias0.CustomerNr) from com.Application.domain.TestData as generatedAlias0 where ( upper(generatedAlias0.CustomerNr) like :param0 ) and ( upper(generatedAlias0.City) like :param1 ) and ( upper(generatedAlias0.Country) like :param2 ) and ( upper(generatedAlias0.UseType) like :param3 ) and ( upper(generatedAlias0.ProjStat) like :param4 ) order by generatedAlias0.CustomerNr asc]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:79)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:255)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1777)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:452)
... 40 more
UPDATE 3
Changing my method gives me the following exception:
#Transactional
#SuppressWarnings("all")
public List<TestData> getCustomerNrFilter(String firstName) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<TestData> criteria = cb.createQuery(TestData.class);
//which table we want to fetch
final Root root = criteria.from(TestData.class);
//create statement
criteria.select(root.get("firstName")).distinct(true);
// Pass the criteria list to the where method of criteria query
criteria.where(cb.and((Predicate[]) criteriaList.toArray(new Predicate[0])));
// Order by clause
criteria.orderBy(cb.asc(root.get("firstName")));
List<String> resultList = em.createQuery(criteria).getResultList(); // EXCPETION: Type mismatch: cannot convert from List<TestData> to List<String>
return resultList;
}
public List createWhereCritera(String firstName, CriteriaBuilder cb,
final Root root) {
// This list will contain all Predicates (where clauses)
List criteriaList = new ArrayList();
// firstName: where condition: TestData.firstName like '%'
Predicate predicateFirstName = cb.like(cb.upper(root.get("firstName")),firstName);
criteriaList.add(predicateFirstName);
return criteriaList;
}

Related

Getting index out of range when trying to call a stored procedure

I've got a query that is supposed to get 2 "tinyint" parameters in-order to run and I wrapped it to be a stored procedure.
the stored procedure in sql goes as follows:
Create Procedure query3
#X tinyint = null,
#Y tinyint = null
AS
BEGIN
SELECT T.tressure_No as 'Treasure Number', T.tressure_Name as 'Treasure Name' , COUNT( DISTINCT U.user_detail_Name) as numOfUsers
FROM dbo.tblUser AS U INNER JOIN dbo.tblTressure AS T
ON U.country_id_user = T.country_Hidden_Code
INNER JOIN dbo.tblListContains AS LC
ON T.tressure_No = LC.tressure_No
AND LC.user_name_detail = U.user_detail_Name
WHERE U.user_detail_Name IN(SELECT LC.user_name_detail
FROM dbo.tblListContains AS LC
WHERE T.tressure_No = LC.tressure_No AND LC.user_name_detail NOT IN (SELECT LF.user_detail_Name
FROM dbo.tblLookingFor AS LF
WHERE LF.tressure_No = T.tressure_No
AND LF.user_detail_Name = U.user_detail_Name)
GROUP BY LC.user_name_detail, LC.tressure_No
HAVING COUNT( LC.num_Of_List_User)>=#Y)
GROUP BY T.tressure_No, T.tressure_Name
Having COUNT( DISTINCT U.user_detail_Name)>=#X;
END
When I test the stored procedure in my 2008 SQLEXPRESS server R2 manager it works just fine and the query inside return's result's as expected.
but when I try to call it from my JAVA GUI it goes to hell...
here is the java code(this method is being called inside my gui to fill a table with the ResultSet):
public ResultSet getQuery3Results(byte numOfUsers, byte numberOfLists){
ResultSet rs = null;
try{
Class.forName(server);
System.out.println("here1");
conn = DriverManager.getConnection(LINK);
String callStatement = "{call query3(?,?)}";
pst.setByte(1, numOfUsers);
pst.setByte(2, numberOfLists);
System.out.println("here2");
pst = conn.prepareCall(callStatement);
rs = pst.executeQuery();
return rs;
}
catch (SQLException ex){
ex.printStackTrace();
rs = null;
return rs;
}
catch (ClassNotFoundException e){
e.printStackTrace();
}
return rs;
}
I get this exception stack trace:
com.microsoft.sqlserver.jdbc.SQLServerException: The index 1 is out of range.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setterGetParam(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setByte(Unknown Source)
at View.ViewLogic.getQuery3Results(ViewLogic.java:1170)
at View.ViewLogic.handleGenerateQuery3Button(ViewLogic.java:1641)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(Unknown Source)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1500(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I have no clue what am I doing wrong, suggestion's and lead's are welcomed :D
Tom
This line needs to happen before setting values
pst = conn.prepareCall(callStatement);
Also, you have to make sure you pass the appropriate data types according to microsoft mapping rules. https://msdn.microsoft.com/en-us/library/ms378878(v=sql.110).aspx
conn = DriverManager.getConnection(LINK);
String callStatement = "{call query3(?,?)}";
pst.setShort(1, numOfUsers);
pst.setShort(2, numberOfLists);

Hazelcast, HazelcastSerializationException: Failed to serialize 'com.hazelcast.spi.impl.operationservice.impl.operations.Backup'

I have created custom entry processor for updating map entries by extending AbstractEntryProcessor.
When my app is running in a cluster on two instances, and the entry processor is executed I receive following exception:
com.hazelcast.nio.serialization.HazelcastSerializationException: Failed to serialize 'com.hazelcast.spi.impl.operationservice.impl.operations.Backup'
at com.hazelcast.internal.serialization.impl.SerializationUtil.handleSerializeException(SerializationUtil.java:73)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toBytes(AbstractSerializationService.java:143)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toBytes(AbstractSerializationService.java:124)
at com.hazelcast.spi.impl.operationservice.impl.OperationServiceImpl.send(OperationServiceImpl.java:406)
at com.hazelcast.spi.impl.operationservice.impl.OperationBackupHandler.sendSingleBackup(OperationBackupHandler.java:187)
at com.hazelcast.spi.impl.operationservice.impl.OperationBackupHandler.makeBackups(OperationBackupHandler.java:159)
at com.hazelcast.spi.impl.operationservice.impl.OperationBackupHandler.backup(OperationBackupHandler.java:78)
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.sendBackup(OperationRunnerImpl.java:270)
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.handleResponse(OperationRunnerImpl.java:253)
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:182)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:122)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.run(OperationThread.java:102)
Caused by: com.hazelcast.nio.serialization.HazelcastSerializationException: Failed to serialize 'com.hazelcast.map.impl.operation.PartitionWideEntryWithPredicateBackupOperation'
at com.hazelcast.internal.serialization.impl.SerializationUtil.handleSerializeException(SerializationUtil.java:73)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.writeObject(AbstractSerializationService.java:201)
at com.hazelcast.internal.serialization.impl.ByteArrayObjectDataOutput.writeObject(ByteArrayObjectDataOutput.java:371)
at com.hazelcast.spi.impl.operationservice.impl.operations.Backup.writeInternal(Backup.java:222)
at com.hazelcast.spi.Operation.writeData(Operation.java:472)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.write(DataSerializableSerializer.java:161)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.write(DataSerializableSerializer.java:52)
at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.write(StreamSerializerAdapter.java:41)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toBytes(AbstractSerializationService.java:140)
... 10 common frames omitted
Caused by: com.hazelcast.nio.serialization.HazelcastSerializationException: Failed to serialize 'com.hazelcast.map.AbstractEntryProcessor$EntryBackupProcessorImpl'
at com.hazelcast.internal.serialization.impl.SerializationUtil.handleSerializeException(SerializationUtil.java:73)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.writeObject(AbstractSerializationService.java:201)
at com.hazelcast.internal.serialization.impl.ByteArrayObjectDataOutput.writeObject(ByteArrayObjectDataOutput.java:371)
at com.hazelcast.map.impl.operation.PartitionWideEntryBackupOperation.writeInternal(PartitionWideEntryBackupOperation.java:98)
at com.hazelcast.map.impl.operation.PartitionWideEntryWithPredicateBackupOperation.writeInternal(PartitionWideEntryWithPredicateBackupOperation.java:51)
at com.hazelcast.spi.Operation.writeData(Operation.java:472)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.write(DataSerializableSerializer.java:161)
at com.hazelcast.internal.serialization.impl.DataSerializableSerializer.write(DataSerializableSerializer.java:52)
at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.write(StreamSerializerAdapter.java:41)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.writeObject(AbstractSerializationService.java:199)
... 17 common frames omitted
Caused by: java.util.ConcurrentModificationException: null
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor143.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor143.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.write(JavaDefaultSerializers.java:242)
at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.write(StreamSerializerAdapter.java:41)
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.writeObject(AbstractSerializationService.java:199)
... 25 common frames omitted
My entry processor is look like this:
public class HRUpdateRacesWithEntriesProcessor extends AbstractEntryProcessor<HRMeeting.HRMeetingKey, HRMeeting> {
private List<HRRace> races;
private Date date;
public HRUpdateRacesWithEntriesProcessor(List<HRRace> races, Date date) {
this.races = races;
this.date = date;
}
#Override
public Object process(Map.Entry<HRMeeting.HRMeetingKey, HRMeeting> entry) {
HRMeeting meeting = entry.getValue();
races.stream()
.filter(race -> entry.getKey().equals(new HRMeeting.HRMeetingKey(race.getMeetingDate(), race.getCourseId())))
.forEach(newRace -> {
Optional<HRRace> matchedRace =
meeting.getRaces().stream().filter(origin -> origin.getKey().equals(newRace.getKey())).findFirst();
if (newRace.getEntries() != null && matchedRace.isPresent()) {
newRace.setUpdateDate(date);
newRace.getEntries().stream()
.filter(hrEntry -> matchedRace.get().getEntries().stream().map(el -> el.getKey())
.collect(Collectors.toList()).contains(hrEntry.getKey()))
.forEach(hrEntry -> hrEntry.setUpdateDate(date));
matchedRace.get().getEntries().retainAll(newRace.getEntries());
newRace.getEntries().addAll(matchedRace.get().getEntries());
}
meeting.getRaces()
.removeIf(hrRace -> matchedRace.isPresent() && matchedRace.get().getKey().equals(hrRace.getKey()));
meeting.getRaces().add(newRace);
});
entry.setValue(meeting);
return null;
}
}
For serialization my entites implements java Serializible. Is is can be reason of the issue?
I am using hazelcast-3.8-SNAPSHOT
Please, help me to solve it.
It might be a simple problem. I met the same error when tried to put an Object to IMap in Hazelcast. In my case, the object, which I try to put, wasn't implements Serializable.
So, I think you should check you did implements Serializable in "com.hazelcast.spi.impl.operationservice.impl.operations.Backup" like
public class Backup implements Serializable {
...
}
I think your problem is that somehow (it actually hard to follow the stream flow) capture content from your EntryProcessor implementation and because of that it is tried to be serialized using Serializable. Anyhow DataSerializable / IdentifiedDataSerializable is not java.util.Serializable to prevent unexpected serialization (like in your case) from happening :)
My guess is the date:
.forEach(hrEntry -> hrEntry.setUpdateDate(date));
I hope this helps, you might have to look for the actually captured value.

JavaFX Reading from file throws "InvocationTargetException"?

I've been trying to understand what the issue is exactly, but whatever I do doesn't seem to work.
I have a text file that lists names along with numbers, seperated by a colon.
An example of this is:
Betty Ross:52
Angie Scotts:29
Michael Rosen:72
The list is very long and comprises over 10,000 lines.
public class PeopleIds {
public static int UNDEFINED_ID = -1;
private static HashMap<String, Integer> people;
public static void initialize() {
people = new HashMap<String, Integer>();
System.out.println(new File("res/ids/people_ids.txt").exists());
try {
Files.lines(Paths.get("res/ids/people_ids.txt")).forEach(s -> {
people.put(s.replaceAll(":.*", "").trim(), Integer.parseInt(s.replaceAll(".*:", "")));
});
} catch (IOException e) {
System.out.println("Unable to read specified file.");
e.printStackTrace();
}
}
public static int getId(final String name) {
final Integer id = people.get(name);
return id != null ? id : UNDEFINED_ID;
}
}
I call the initialize method from a GUIController class:
public class GUIController implements Initializable {
#FXML
private TableView<PersonData> personTable;
#FXML
private TableColumn<PersonData, String> name;
#FXML
private TableColumn<PersonData, Integer> limit;
#FXML
private TextField searchInput;
#FXML
private ImageView personIcon;
private Image undefinedIcon;
private PersonIcon icon;
private ObservableList<PersonData> data;
#Override
public void initialize(URL location, ResourceBundle resources) {
PeopleIds.initialize();
undefinedIcon = new Image(getClass().getResourceAsStream("/ids/no.png"));
name.setCellValueFactory(new PropertyValueFactory<PersonData, String>("name"));
limit.setCellValueFactory(new PropertyValueFactory<PersonData, Integer>("limit"));
data = PriceData.getData();
personTable.setPeople(data);
searchInput.textProperty().addListener((ov, oldValue, newValue) -> {
final String input = searchInput.getText();
if (input.length() == 0) return;
searchInput.setText(input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase());
filterSearch();
});
}
}
When I call it from this class with PeopleIds.initialize(), an exception is thrown, telling me that there was an exception in the application start method.
Here is what was logged in its entirety:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$156(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: javafx.fxml.LoadException:
/C:/Confidential/bin/base/PersonGUI.fxml
at javafx.fxml.FXMLLoader.constructLoadException(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at base.PersonGUI.start(PersonGUI.java:13)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$163(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$174(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(Unknown Source)
... 1 more
Caused by: java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1
at java.io.BufferedReader$1.hasNext(Unknown Source)
at java.util.Iterator.forEachRemaining(Unknown Source)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
at java.util.stream.ReferencePipeline$Head.forEach(Unknown Source)
at base.PeopleIds.initialize(PeopleIds.java:17)
at base.GUIController.initialize(GUIController.java:36)
... 18 more
Caused by: java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
... 24 more
Exception running application base.PersonGUI
I'm not sure what is going on here? I've looked into it and people have said to move the fxml file (the one that is used to format the content and is linked with the GUIController to the same package as the Main class, however it already is.
I've been wrestling with this issue for days to no avail. Do any of you have past experiences with this issue? If so, how did you resolve it? Thanks a lot.
If there is an Exception while the file is being read, not when opening the file, an unchecked exception is thrown for the Files.lines stream operation (Stream.forEach doesn't have a throws clause).
This happens here
Files.lines(Paths.get("res/ids/people_ids.txt")).forEach(s -> {
people.put(s.replaceAll(":.*", "").trim(), Integer.parseInt(s.replaceAll(".*:", "")));
});
, which you can easily see in the stacktrace:
Caused by: java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1
(This is caused by the wrong Charset being used, see Files.readAllBytes vs Files.lines getting MalformedInputException )
You don't catch this kind of exception with your catch clause:
} catch (IOException e) {
You need to use
} catch (Exception e) {
to catch the unchecked exceptions too.

Storing object in database in Java

I am trying to store my object in MySQL database using java language. I am trying to convert object into byte so I can store it into LONGBLOB. But I am facing error i.e "NotSerializable Exception".
My Class whose object I want to sore:
public class Books implements Serializable {
private int isbn;
private String bookName;
private String author;
private String edition;
private int rowNo;
private int colNo;
private String shelfNo;
private String img;
private InputStream imag;
validation v = new Validation();
Database database;
public Books() { database = new Database(); }
.
.
setters & getters...
Method to call database method to insert object in database:
String className = this.getClass().getName();
database.insertBookRecord(this.getIsbn(), this, className);
this is the object of current class which I want to store.
following is the insertBookRecord method.
public void insertBookRecord(int isbn, Books book, String name) {
String query = "INSERT INTO Test VALUES (?, ?, ?)";
byte[] data = null;
//book = new Books();
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(book);
oos.flush();
oos.close();
baos.close();
data = baos.toByteArray();
}
catch(IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
try {
//conn.setAutoCommit(false);
state = conn.prepareStatement(query);
state.setInt(1, isbn);
state.setString(2, name);
state.setObject(3, data);
state.executeUpdate();
//conn.commit();
}
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
finally {
close(3);
}
}
When I reach at statement oos.writeObject(book); Its stops with exception and displays the the package & Classname in the JOptionPane.
My book object has all the data fields I entered in the text fields. But I am unable to write it./convert it into Serializable format.
Any suggestions please?
Stack Trace:
java.io.NotSerializableException: com.my.classes.Database
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.my.classes.Database.insertBookRecord(Database.java:123)
at com.my.classes.Books.insertBookRecord(Books.java:107)
at com.my.jlms.ManageBooks$2.actionPerformed(ManageBooks.java:308)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
You get the exception because you are trying to serialize an InputStream
private InputStream imag;
InputStream is not Serializable
You could omit this field when serializing by declaring it transient:
private transient InputStream imag;
Your imag is InputStream which is not implement Serializable. It should be a byte[] or String link to your imag location.
Edited: You should separate business from model object. Move insertBook method and database object from Book class to another class.
So the problem was InputStream as well as i was trying to Seralize the objects i.e V & database.
I just added transient e.g private transient Database database; and then declared database = new Database(); in the constructor. hence I was able to serialize it.
Thank you #Ralf, #Joseph, #Diyarbakir and #3kings for helping me out.

NullPointerException when unmarshalling different attributes types to the same java object

I'm having a serious issue while trying to unmarshal an XML. At first, the Member elements contained only Integer in their "value" attributes (like the first 'EnumType' element), however, now that another 'EnumType' appears with Strings as the value - I'm getting the bellow NullPointerException.
Notice, that the 'value' member in Member.java was from type "int" at the beginning (when only Integer was accepted as values of the Member element) and it worked fine. Only when I have changed it to Object (and I guess this is the source of my issue) - the below exception was appeared.
XML:
<EnumType Name="Genre" UnderlyingType="Edm.Int32">
<Member Name="ACTION" Value="0"/>
<Member Name="COMEDY" Value="1"/>
</EnumType>
<EnumType Name="Rating" UnderlyingType="Edm.String">
<Member Name="RatingA" Value="G"/>
<Member Name="RatingB" Value="PG"/>
</EnumType>
EnumType.java
#XmlRootElement
public class EnumType {
#XmlElement(name = "Member", namespace = "http://schemas.microsoft.com/ado/2009/11/edm")
private List<Member> members = new LinkedList<Member>();
public List<Member> getMembers() {
return members;
}
}
Member.Java
#XmlRootElement
public class Member {
#XmlAttribute(name = "Name")
private String name;
#XmlAttribute(name = "Value")
private Object value;
public String getName() {
return name;
}
public Object getValue() {
return value;
}
}
When unmarshaling the above XML I'm getting this NullPointerException:
java.lang.NullPointerException
at com.sun.xml.internal.bind.v2.runtime.reflect.TransducedAccessor.get(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.property.AttributeProperty.(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.property.PropertyFactory.create(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayElementProperty.(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayElementNodeProperty.(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.property.PropertyFactory.create(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayElementProperty.(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.property.ArrayElementNodeProperty.(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.property.PropertyFactory.create(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.property.SingleElementNodeProperty.(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.property.PropertyFactory.create(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.property.SingleElementNodeProperty.(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.property.PropertyFactory.create(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getOrCreate(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(Unknown Source)
at com.sun.xml.internal.bind.v2.ContextFactory.createContext(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.newInstance(Unknown Source)
at javax.xml.bind.ContextFinder.find(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at javax.xml.bind.JAXBContext.newInstance(Unknown Source)
at com.sap.ndb.studio.rdl.csdlparser.jaxb.JAXBParser.load(JAXBParser.java:26)
at com.sap.ndb.studio.rdl.datapreview.functions.LoadGRDL.function(LoadGRDL.java:59)
at org.eclipse.swt.browser.WebSite.Invoke(WebSite.java:773)
at org.eclipse.swt.browser.WebSite$7.method6(WebSite.java:129)
at org.eclipse.swt.internal.ole.win32.COMObject.callback6(COMObject.java:119)
at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method)
at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:2546)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3756)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2701)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2665)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2499)
at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:679)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:668)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
at org.eclipse.equinox.launcher.Main.main(Main.java:1414)
Any ideas? :(
The JAXB RI will throw that exception when you annotate a field/property of type Object with #XmlAttribute. Like you have in your Member class:
#XmlAttribute(name = "Value")
private Object value;
For More Information
JAXB attribute with Object type throwing null pointer exception?

Categories