Saving List of Objects Throws Hibernate Exception - java

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.

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'

java.lang.IndexOutOfBoundsException: Index: 5, Size: 5

I am having an issue with arrays. The full stack trace is:
java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
at java.util.ArrayList.rangeCheck(Unknown Source) ~[?:1.7.0_79]
at java.util.ArrayList.get(Unknown Source) ~[?:1.7.0_79]
at xyz.lexium.brocubes.drops.DropDB.getRandomDrop(DropDB.java:17) ~[DropDB.class:?]
at xyz.lexium.brocubes.blocks.BroBlock.onBlockDestroyedByPlayer(BroBlock.java:33) ~[BroBlock.class:?]
at net.minecraft.client.multiplayer.PlayerControllerMP.onPlayerDestroyBlock(PlayerControllerMP.java:187) ~[PlayerControllerMP.class:?]
at net.minecraft.client.multiplayer.PlayerControllerMP.func_178891_a(PlayerControllerMP.java:68) ~[PlayerControllerMP.class:?]
at net.minecraft.client.multiplayer.PlayerControllerMP.func_180511_b(PlayerControllerMP.java:232) ~[PlayerControllerMP.class:?]
at net.minecraft.client.Minecraft.clickMouse(Minecraft.java:1519) ~[Minecraft.class:?]
at net.minecraft.client.Minecraft.runTick(Minecraft.java:2126) ~[Minecraft.class:?]
at net.minecraft.client.Minecraft.runGameLoop(Minecraft.java:1087) ~[Minecraft.class:?]
at net.minecraft.client.Minecraft.run(Minecraft.java:376) [Minecraft.class:?]
at net.minecraft.client.main.Main.main(Main.java:117) [Main.class:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_79]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0_79]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0_79]
at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.7.0_79]
at net.minecraft.launchwrapper.Launch.launch(Launch.java:135) [launchwrapper-1.12.jar:?]
at net.minecraft.launchwrapper.Launch.main(Launch.java:28) [launchwrapper-1.12.jar:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_79]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0_79]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0_79]
at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.7.0_79]
at net.minecraftforge.gradle.GradleStartCommon.launch(Unknown Source) [start/:?]
at GradleStart.main(Unknown Source) [start/:?]
The code I use for this is:
DropBase drop = DropDB.getRandomDrop();
for (int i = 1; i < drop.getDrops().size() -1; i++) {
EntityItem item = new EntityItem(worldIn, pos.getX(), pos.getY() + 1, pos.getZ(), drop.getDrops().get(i));
System.out.println(i);
worldIn.spawnEntityInWorld(item);
This code calls DropDB and selects a random drop from a registered list. The list is perfectly fine. Here is the code for getDrop is:
public static DropBase getRandomDrop() {
Random rand = new Random();
int n = rand.nextInt(drops.size()) + 1;
System.out.println(n);
System.out.println(drops.size());
return drops.get(n);
}
This code causes this error. I have tired to look at the other questions around here. They have not worked.
Indices in Java are 0-based the valid values are 0 to size() - 1. When you generate a new random number you should not + 1 you want a range of 0 to size() -1.
I was having similar issues with an array. I believe it has to do with the for loop itself, quite not sure though, feel free to correct.
The equivalent of what solved my issue would be this :
Look at this part
for (int i = 1; i < drop.getDrops().size() -1; i++)
I would do this instead :
Int dropsSize = drop.getDrops().size() - 1; // just to keep it clean
// but you don't have to do this.
for (int **i = 0**; i < dropsSize ; i++) {

How to load HashMap properly from a .yml file?

I am trying to load a HashMap from the config file using the standard Bukkit configuration files API.
HashMap:
public static HashMap<String, String> banned = new HashMap<String, String>();
This is the way I am trying to get the data:
public static boolean isBanned(String uuid) {
if (Dogends.config.getConfigurationSection("Banned").getKeys(true).contains(uuid)) {
return true;
}
return false;
}
If the player is banned then it's ok, but when the player is not banned, then it throws a NullPointerException out.
NullPointerException:
Could not pass event PlayerLoginEvent to Dogends v1.0
org.bukkit.event.EventException
at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:302) ~[cb.jar:git-Bukkit-880a532]
at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.java:62) ~[cb.jar:git-Bukkit-880a532]
at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.java:501) [cb.jar:git-Bukkit-880a532]
at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.java:486) [cb.jar:git-Bukkit-880a532]
at net.minecraft.server.v1_8_R3.PlayerList.attemptLogin(PlayerList.java:439) [cb.jar:git-Bukkit-880a532]
at net.minecraft.server.v1_8_R3.LoginListener.b(LoginListener.java:89) [cb.jar:git-Bukkit-880a532]
at net.minecraft.server.v1_8_R3.LoginListener.c(LoginListener.java:53) [cb.jar:git-Bukkit-880a532]
at net.minecraft.server.v1_8_R3.NetworkManager.a(NetworkManager.java:222) [cb.jar:git-Bukkit-880a532]
at net.minecraft.server.v1_8_R3.ServerConnection.c(SourceFile:168) [cb.jar:git-Bukkit-880a532]
at net.minecraft.server.v1_8_R3.MinecraftServer.B(MinecraftServer.java:744) [cb.jar:git-Bukkit-880a532]
at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:335) [cb.jar:git-Bukkit-880a532]
at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:628) [cb.jar:git-Bukkit-880a532]
at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:536) [cb.jar:git-Bukkit-880a532]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_91]
Caused by: java.lang.NullPointerException
at me.woulfiee.server.ban.BanCommand.isBanned(BanCommand.java:47) ~[?:?]
at me.woulfiee.server.ban.BanCommand.onPlayerLogin(BanCommand.java:103) ~[?:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_91]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_91]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_91]
at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_91]
at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:300) ~[cb.jar:git-Bukkit-880a532]
... 13 more
config.yml:
Ranks:
Player:
Players: []
Mythic:
Players: []
Doge:
Players: []
Youtuber:
Players: []
Builder:
Players: []
Mod:
Players: []
Admin:
Players: []
Owner:
Players:
- d166739c-32d3-4b37-a1be-883be57d736c
Broadcast:
Interval: 120
Banned:
d166739c-32d3-4b37-a1be-883be57d736c: "CONSOLE \xa7eHELP"
To accomplish what you wish, you should try the following:
Make sure your config is not null/exists
boolean isBanned(String uuid) {
FileConfiguration yourConfig;
//Getting the Banned section
ConfigurationSection banned = yourConfig.getConfigurationSection("Banned");
//All the keys inside the banned configuration section
Set<String> keys = banned.getKeys(false); //We don't want it to be deep
if (keys.contains(uuid))return true; //UUID is on the keys list, so the player is banned
return false; //UUID is not on the keys list, so the player is not banned
}
I don't believe you actually need the hashmap, unless you're using it for something else
getConfigurationSection:
If the ConfigurationSection does not exist but a default value has
been specified, this will return the default value. If the
ConfigurationSection does not exist and no default value was
specified, this will return null.
I'm guessing if there are no users banned, there is no Banned section, so getConfigurationSection returns null, which is why your getKeys() call throws a NPE.
So you should first check if the configuration section exists, and only then try to use it.

Handle NullPointerException on reading null value from zoho reports database [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Chatlet Created
Chatlet Thrown
Inside reply
5684dc24617149a601dea913 Yes, Please let me in.
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.teamchat.client.sdk.impl.TeamchatAPIImpl.invokeMethod(Unknown Source)
at com.teamchat.client.sdk.impl.TeamchatAPIImpl.onMsg(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamConnector.onMsg(Unknown Source)
at com.teamchat.client.sdk.impl.SimpleEventsExecutor.notifyCallbackMessage(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamImpl.handleLine(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamImpl.fetchEventStream(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamImpl.fetchOnceAndReturnInterruptedStatus(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamConnector.getEvents(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamConnector.mainloop(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamConnector.access$000(Unknown Source)
at com.teamchat.client.sdk.events.EventStreamConnector$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at frontEnd.sendRequest.onReply(sendRequest.java:75)
... 16 more
I am currently working on task where I need to throw some message on reading null value from the database cell. But When I try to do so my code throws NullPointerException. I tried to handle it using try catch block but nothing helped me.
public String getCellData(String sql_query) throws Exception {
System.out.println("Inside getCellData");
String cell_data = "";
try{
JSONArray queried_data = (JSONArray)db_work.retrieveQueryRows(db_work.retrieveData(sql_query).toString());
for (int i = 0; i < queried_data.size(); i++) {
JSONArray queried_row=(JSONArray) queried_data.get(i);
cell_data = queried_row.get(0).toString();
}
}
catch(NullPointerException e)
{
cell_data="empty";
return cell_data;
}
return cell_data;
}
if(response.equals("Yes, Please let me in.")){
String gender = fetch_details.getCellData("select * from Group_Join where Room='"+room_id+"'");
System.out.println(gender);
String goal = fetch_details.getCellData("select * from Group_Join where Room='"+room_id+"'");
System.out.println(goal);
api.performPostInCurrentRoom(new TextChatlet("Sure, thanks. We will add you to the support group."));
if (goal.equals("empty")) {
if (gender.equals("empty")) {
System.out.println("Gender and Goal Both Empty");
PrimaryChatlet gender_goal_chatlet=new PrimaryChatlet();
gender_goal_chatlet.alias("GenderGoal");
Form gender_goal_form=api.objects().form();
gender_goal_form.addField(api.objects().select().name("Goal").label("Goal").addOption("Weight Loss").addOption("Weight Gain").addOption("Muscle Tone"));
gender_goal_form.addField(api.objects().select().name("Gender").label("Gender").addOption("Male").addOption("Female"));
gender_goal_chatlet.setReplyScreen(gender_goal_form);
api.performPostInCurrentRoom(gender_goal_chatlet);
}
It isn't recommended to catch a runtime exception (which your NullPointerException is).
Why don't you try to avoid it in the first place?
Something like:
if (queried_row.get(0).toString() != null)
cell_data = queried_row.get(0).toString();
else
cell_data = "empty";
or
cell_data = (queried_row.get(0).toString() != null) ? queried_row.get(0).toString() : "empty";

Delete data HQL with setParameter or setParametrList strangeness

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.

Categories