Delete data HQL with setParameter or setParametrList strangeness - java

I have a simple table and try to delete data by array of ids.
Integer[] arrayIDs = {1,2,3}; //External ids as parameteres
Query deleteItemsQuery = session.createQuery("DELETE Items WHERE id IN (:idsDeletingItems)"); //(in this row exception)
deleteItemsQuery.setParameterList("idsDeletingItems", arrayIDs);
deleteItemsQuery.executeUpdate();
And my app throw exception
I also try with deleting 1 parameter. For example
Query deleteItemsQuery = session.createQuery("DELETE Items WHERE id = '1'");
deleteItemsQuery.executeUpdate();
And with that variant no problem.
But when I do next I have also exception
Integer myID = 1;
Query deleteItemsQuery = session.createQuery("DELETE Items WHERE id = (:myID)");
deleteItemsQuery.setParameter("myID", myID);
deleteItemsQuery.executeUpdate();
I use this dialect org.hibernate.dialect.Oracle10gDialect. Any ideas?
Exception
exception
javax.servlet.ServletException: java.lang.NoSuchMethodError: antlr.collections.AST.getLine()I
org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:295)
org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:113)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
com.epam.testapp.presentation.filter.CharsetFilter.doFilter(CharsetFilter.java:44)
com.epam.testapp.presentation.filter.CommandFilter.doFilter(CommandFilter.java:58)
root cause
java.lang.NoSuchMethodError: antlr.collections.AST.getLine()I
org.hibernate.hql.internal.ast.HqlSqlWalker.generateNamedParameter(HqlSqlWalker.java:956)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.parameter(HqlSqlBaseWalker.java:4821)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1347)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4297)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:3772)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:1947)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:794)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.deleteStatement(HqlSqlBaseWalker.java:443)
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:263)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:219)
org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:197)
org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1736)
com.epam.testapp.database.NewsHibernateDAO.remove(NewsHibernateDAO.java:89)
com.epam.testapp.presentation.action.NewsAction.delete(NewsAction.java:150)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:113)
org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

Make it like this
Integer myID = 1;
Query deleteItemsQuery = session.createQuery("DELETE Items WHERE id =:myID");
deleteItemsQuery.setParameter("myID", myID);
deleteItemsQuery.executeUpdate();
and make sure no space between ":" and "myID" else it will another error.
Hope it helps ;-)

I also ran into this problem once and worked around it by adding the opening and closing brace to my parameter in stead of placing it directly in the HQL.

Related

Nullpointer Error in groovy script while trying to add xpath assertion

I am getting an error as
java.lang.NullPointerException: Cannot invoke method getAssertionByName() on null object error at line: 5
however I am able to add xpath assertion in the test case.
As, I am new to groovy so want to know :-
What is the reason that I am getting this error.
How can I implement a code for select from current option in xpath assertion so that i can add xpath instead of printing some junk value(i have printed "hello" as of now).
log.info("Testing Start")
def project = context.testCase.testSuite.project
TSName = "ManagePostpayInsurance_1_0"
StepName = "getInsuranceDetails_FC_004"
project.getTestSuiteList().each {
if(it.name == TSName) {
TS = it.name
it.getTestCaseList().each {
TC =it.name
def asserting = project.getTestSuiteByName(TS).getTestCaseByName(TC).getTestStepByName(StepName).getAssertionByName("XPath Match")
log.info(asserting)
if (asserting instanceof com.eviware.soapui.impl.wsdl.teststeps.assertions.basic.XPathContainsAssertion){
project.getTestSuiteByName(TS).getTestCaseByName(TC).getTestStepByName(StepName).removeAssertion(asserting)
}
def assertion = project.getTestSuiteByName(TS).getTestCaseByName(TC)getTestStepByName(StepName).addAssertion("XPath Match")
assertion.path = "declare namespace cor='http://soa.o2.co.uk/coredata_1';\ndeclare namespace man='http://soa.o2.co.uk/managepostpayinsurancedata_1';\ndeclare namespace soapenv='http://schemas.xmlsoap.org/soap/envelope/';\n//man:getInsuranceDetails_1Response"
assertion.expectedContent = "hello"
}
}
}
log.info("Testing Over")
I have attached the error log below.
Mon Nov 27 17:04:12 IST 2017:ERROR:java.lang.NullPointerException: Cannot invoke method getAssertionByName() on null object
java.lang.NullPointerException: Cannot invoke method getAssertionByName() on null object
at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:77)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:45)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:32)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at com.eviware.soapui.model.testsuite.Assertable$getAssertionByName.call(Unknown Source)
at Script10$_run_closure1_closure2.doCall(Script10.groovy:11)
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.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:909)
at groovy.lang.Closure.call(Closure.java:411)
at groovy.lang.Closure.call(Closure.java:427)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1325)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1297)
at org.codehaus.groovy.runtime.dgm$148.invoke(Unknown Source)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:271)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at Script10$_run_closure1.doCall(Script10.groovy:9)
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.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:909)
at groovy.lang.Closure.call(Closure.java:411)
at groovy.lang.Closure.call(Closure.java:427)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1325)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1297)
at org.codehaus.groovy.runtime.dgm$148.invoke(Unknown Source)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:271)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at Script10.run(Script10.groovy:5)
at com.eviware.soapui.support.scripting.groovy.SoapUIGroovyScriptEngine.run(SoapUIGroovyScriptEngine.java:90)
at com.eviware.soapui.impl.wsdl.teststeps.WsdlGroovyScriptTestStep.run(WsdlGroovyScriptTestStep.java:141)
at com.eviware.soapui.impl.wsdl.panels.teststeps.GroovyScriptStepDesktopPanel$RunAction$1.run(GroovyScriptStepDesktopPanel.java:250)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I'm badly stuck with the above issue, quick help is really appreciated!!!!
Thank you very much
Here you go:
Since you are going thru hierarchically, do not require to refer full chain of methods starting from project.
Instead, you could directly access the step objects once you browse to step level. This way, NPE can be avoided.
Here is the fixed script, see the inline relevant comment.
import com.eviware.soapui.impl.wsdl.teststeps.assertions.basic.XPathContainsAssertion
log.info("Testing Start")
def project = context.testCase.testSuite.project
def suiteName = "ManagePostpayInsurance_1_0"
def stepName = "getInsuranceDetails_FC_004"
project.testSuiteList.each { suite ->
if(suiteName == suite.name) {
suite.testCaseList.each { kase ->
kase.testStepList.each { step ->
if (stepName == step.name) {
//Note the change here, directly getting the object from step object
def asserting = step.getAssertionByName("XPath Match")
log.info(asserting)
if (asserting instanceof XPathContainsAssertion){
step.removeAssertion(asserting)
}
def assertion = step.addAssertion("XPath Match")
assertion.path = "declare namespace cor='http://soa.o2.co.uk/coredata_1';\ndeclare namespace man='http://soa.o2.co.uk/managepostpayinsurancedata_1';\ndeclare namespace soapenv='http://schemas.xmlsoap.org/soap/envelope/';\n//man:getInsuranceDetails_1Response"
assertion.expectedContent = "hello"
}
}
}
}
}
log.info 'Testing Over'

How to return distance and score in spatial search using spring-data-solr

I'm writing a Spring MVC based Search API using spring-data-solr 1.0.0.RELEASE with Solr 4.4.0 and Spring 3.2.4.RELEASE.
I'm able to run basic queries but unable to find any good example how can I return score and distance:geodist() in the results.
I know I can get results from Solr using query like
http://localhost:8983/solr/events/select?q=*:*&spatial=true&pt=51.435872%2C-0.427529&sfield=position&d=20&facet=true&facet.mincount=1&facet.limit=-1&facet.field=categoryIds&fl=score,*,distance:geodist()&sort=geodist()+asc
but I don't know how to get score and distance properties returned from Solr using spring-data-solr. I have tried following code
FacetQuery search = new SimpleFacetQuery();
Criteria conditions;// = new Criteria();
if(StringUtils.isNotBlank(searchCriteria.getSearchString()))
conditions = new Criteria(EventDocument.FIELD_EVENT).contains(searchCriteria.getSearchString());
if(searchCriteria.isLocationKnown()){
conditions.and(new Criteria(EventDocument.FIELD_POSITION).within(new GeoLocation(searchCriteria.getLatitude(), searchCriteria.getLongitude()), new Distance(searchCriteria.getDistance(), Distance.Unit.MILES)));
conditions.and(new Criteria(CommonParams.FL).is("score,distance:geodist(),*"));
} else{
conditions.and(new Criteria(CommonParams.FL).is("score,*"));
}
search.addCriteria(conditions);
FacetPage page = solrTemplate.queryForFacetPage(search, EventDocument.class);
but getting following Exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.data.solr.UncategorizedSolrException: undefined field fl; nested exception is org.apache.solr.client.solrj.impl.HttpSolrServer$RemoteSolrException: undefined field fl
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
org.springframework.data.solr.UncategorizedSolrException: undefined field fl; nested exception is org.apache.solr.client.solrj.impl.HttpSolrServer$RemoteSolrException: undefined field fl
org.springframework.data.solr.core.SolrTemplate.execute(SolrTemplate.java:122)
org.springframework.data.solr.core.SolrTemplate.executeSolrQuery(SolrTemplate.java:330)
org.springframework.data.solr.core.SolrTemplate.query(SolrTemplate.java:326)
org.springframework.data.solr.core.SolrTemplate.queryForFacetPage(SolrTemplate.java:285)
com.johnstonpress.api.repository.EventDocumentRepositoryImpl.search(EventDocumentRepositoryImpl.java:72)
com.johnstonpress.api.service.SearchEventServiceImpl.search(SearchEventServiceImpl.java:106)
com.johnstonpress.api.controller.EventsSearchController.searchEvents(EventsSearchController.java:124)
com.johnstonpress.api.controller.EventsSearchController.search(EventsSearchController.java:68)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Thanks for any attention and help!!!
To set fl you have to use query.addProjectionOnField(String fieldname).
SimpleQuery query = new SimpleQuery(conditions);
query.addProjectionOnField("*");
query.addProjectionOnField("score");
For mapping score into EventDocument you'll have to add the property as follows.
#Indexed(value = "score", readonly = true)
private Float score;
Unfortunately there seems to be an issue with geodist() that might be caused by the way spring data solr creates spatial query.
Opended DATASOLR-130 for that.
Distance can be requested using SolrCallback along with SolrTemplate by setting spatial paramters yourself.
SimpleQuery query = new SimpleQuery(conditions);
query.addProjectionOnField("*");
query.addProjectionOnField("distance:geodist()");
DefaultQueryParser qp = new DefaultQueryParser();
final SolrQuery solrQuery = qp.constructSolrQuery(query);
solrQuery.add("sfield", "store");
solrQuery.add("pt", GeoConverters.GeoLocationToStringConverter.INSTANCE.convert(new GeoLocation(45.15, -93.85)));
solrQuery.add("d", GeoConverters.DistanceToStringConverter.INSTANCE.convert(new Distance(5)));
List<EventDocument> result = template.execute(new SolrCallback<List<EventDocument>>() {
#Override
public List<EventDocument> doInSolr(SolrServer solrServer) throws SolrServerException, IOException {
return template.getConverter().read(solrServer.query(solrQuery).getResults(), EventDocument.class);
}
});
A litte bit easier would be to provide required parameters for geodist().
SimpleQuery query = new SimpleQuery(conditions);
query.addProjectionOnField("*");
query.addProjectionOnField("distance:geodist(store," + GeoConverters.GeoLocationToStringConverter.INSTANCE.convert(new GeoLocation(45.15, -93.85)) + ")");
Page<EventDocument> result = template.queryForPage(query, EventDocument.class);
hope that helps!

HQL query for Distinct records

pls i get this error any time i run my application ....any help pls.
java.lang.IllegalArgumentException: node to traverse cannot be null!
org.hibernate.hql.internal.ast.util.NodeTraverser.traverseDepthFirst(NodeTraverser.java:63)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:272)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:180)
org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:119)
org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:214)
org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:192)
org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1537)
org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:285)
sun.reflect.GeneratedMethodAccessor31.invoke(Unknown Source)
this is the code i av in my repository class
#Query("distinct v from voucher v where v.voucherType.typeID = :typeID ")
public List<Voucher> findDistinctByVoucherType(#Param("typeID") Long voucherTypeId);
There is no issue with query. The above exception indicates that
distinct v from voucher v where v.voucherType.typeID = :typeID
is not returning any result

Saving List of Objects Throws Hibernate Exception

When I am saving a List of objects by calling saveListOfPageChooserElement, it throws the below exception
Whereas, when I am saving a single instance by calling saveOrUpdate, then it works fine.
But to improve performance I want to save a List batch rather than single object at a time.
Can anyone suggest what's the problem with saving a whole list at once?
List<Abc> listabc = widgetCopyDAO
.fetchabcByPageId(id);
for (Abc abc: listabc ) {
abc.setLastUpdatedBy(null);
abc.setLastUpdatedOn(null);
abc.setCreatedBy(widgetCopyDTO.getUserName());
abc.setCreatedOn(new Date());
abc.setPageChooser(new PageChooser(chooser.getId()));
abc.setId(0l);
issuePageWidgetDAO.saveOrUpdate(abc);
}
// widgetCopyDAO.saveListOfPageChooserElement(listabc);
public void saveOrUpdate(Abc abc) {
if (abc.getId() == 0) {
Long id = (Long) this.getHibernateTemplate().save(
abc);
abc.setId(id);
} else {
this.getHibernateTemplate().update(abc);
}
}
public void saveListOfPageChooserElement(
List<Abc> listabc) {
this.getHibernateTemplate().saveOrUpdateAll(listabc);
}
The exception is
org.springframework.orm.hibernate3.HibernateSystemException: identifier of an instance of com.mct.model.Abc was altered from 138 to 0; nested exception is org.hibernate.HibernateException: identifier of an instance of com.mct.model.Abc was altered from 138 to 0
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:676)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:424)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1055)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1048)
at com.mct.dao.WidgetCopyDAO.fetchPageChooserWithImagesByChooser(WidgetCopyDAO.java:82)
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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
at org.springframework.aop.framework.adapter.ThrowsAdviceInterceptor.invoke(ThrowsAdviceInterceptor.java:126)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:50)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:50)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy58.fetchPageChooserWithImagesByChooser(Unknown Source)
at com.mct.service.widgethelper.ChooserWidget.copyWidget(ChooserWidget.java:676)
at com.mct.service.widgethelper.ChooserWidget.copyAllWidgets(ChooserWidget.java:634)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown
You set ht Ids of all objects in the list:
abc.setId(0l);
And that's what causes the error.
You cannot change an auto-generated ID by your own.
Remove this line.
In hibernate You can't set Id (Autogenrated) manulally like below.
abc.setId(0l);
Remove this above line try again.
The problem appears to be this line:
abc.setId(0l);
You are clearing the ids of the entities you've loaded from the database.

can't write dom document to xml file

I have spring mvc project in whicn I upload xml file and try to write it to the my xml by DOM, but confront with this exception. When I make attempts to do the same proccesses in usual project - all works fine. Can't understand why it happens..
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause
java.lang.NullPointerException
org.apache.xml.utils.TreeWalker.dispatachChars(TreeWalker.java:303)
org.apache.xml.utils.TreeWalker.startNode(TreeWalker.java:447)
org.apache.xml.utils.TreeWalker.traverse(TreeWalker.java:202)
org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:343)
com.mycompany.xmlloader.xmlHandler.DOMParser.saveToCatalog(DOMParser.java:147)
com.mycompany.xmlloader.service.XMLServiceImpl.updateCatalog(XMLServiceImpl.java:48)
com.mycompany.xmlloader.controller.XMLController.uploadToCatalog(XMLController.java:47)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
And snippet of code:
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(catalogFile.toURI().getPath());
Source source = new DOMSource(doc);
trans.transform(source, result);
The likely cause of your problem is a Text node in your Document which has its data set to null. (See here and here for discussions of the problem.)
You can check your Document to see if this diagnosis is correct using the following code:
public static void checkDoc(Node n) {
if (n instanceof Text) {
if (((Text) n).getData() == null) {
System.err.println("null data!!!!");
}
}
NodeList l = n.getChildNodes();
for (int i = 0; i < l.getLength(); ++i) {
checkDoc(l.item(i));
}
}
Call checkDoc on your Document:
checkDoc(doc);
If you see any output, then you now know the immediate cause for your NPE. The solution to your problem is then: Do not build a Document containing Text nodes with null data.

Categories