Retry test case using TestNG while using ITestContext with test method - java

I am using dataprovider method and a test method (with ITestContext parameter in the test method). A simplified example is as follows :
#DataProvider(name="Dataprovider")
public Object[][] dataprovider(){
return new Object[][]{{1},{2,},{3}};
}
#Test(dataProvider="Dataprovider")
public void test(int data, ITestContext itx){
System.out.println(data);
org.testng.Assert.assertEquals(data, 3);
}
My Retry class and RetryListener classes are below :
public class RetryListener implements IAnnotationTransformer {
#Override
public void transform(ITestAnnotation testannotation, Class testClass,
Constructor testConstructor, Method testMethod) {
IRetryAnalyzer retry = testannotation.getRetryAnalyzer();
if (retry == null) {
testannotation.setRetryAnalyzer(Retry.class);
}
}
}
public class Retry implements IRetryAnalyzer {
private static int retryCount = 0;
private int maxRetryCount = 1;
// Below method returns 'true' if the test method has to be retried else 'false'
//and it takes the 'Result' as parameter of the test method that just ran
public boolean retry(ITestResult result) {
if (retryCount < maxRetryCount) {
System.out.println("Retrying test " + result.getName() + " with status "
+ getResultStatusName(result.getStatus()) + " for the " + (retryCount+1) + " time(s).");
retryCount++;
return true;
}
retryCount = 0;
return false;
}
public String getResultStatusName(int status) {
String resultName = null;
if(status==1)
resultName = "SUCCESS";
if(status==2)
resultName = "FAILURE";
if(status==3)
resultName = "SKIP";
return resultName;
}
}
Expected : When test fails, the retry is called by TestNG, then the dataprovider should return the same values to the test method.
Observed : Dataprovider returns the same value but test method doesn't run and the retry terminates and next test starts (new values will now be returned by dataprovider)
But my retry does not enter the test method ( It is not expecting the (int data, ITestContext itx) for test method). If I remove ITestContext, the retry works.
ITestContext is a must for maintaining the test case context. So how to perform retry along with keeping the ITestContext in the test method.

Within a #Test method that's powered by a data provider, I think its difficult to put the ITestContext as an explicit parameter and expect it to be injected by TestNG, because TestNG wouldn't know how to inject it (especially at which position).
Please see if the below would work for you (If you notice, I am now explicitly also passing in the ITestContext via the data provider )
import org.testng.IRetryAnalyzer;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class RetryWithDataProvider {
#DataProvider(name = "Dataprovider")
public Object[][] dataprovider(ITestContext ctx) {
return new Object[][]{{1, ctx}, {2, ctx}, {3, ctx}};
}
#Test(dataProvider = "Dataprovider", retryAnalyzer = Retry.class)
public void test(int data, ITestContext itx) {
System.out.println(data);
System.out.println("Current Test name is : " + itx.getName());
org.testng.Assert.assertEquals(data, 3);
}
public static class Retry implements IRetryAnalyzer {
private static int retryCount = 0;
private int maxRetryCount = 1;
public boolean retry(ITestResult result) {
if (retryCount < maxRetryCount) {
System.out.println("Retrying test " + result.getName() + " with status "
+ getResultStatusName(result.getStatus()) + " for the " + (retryCount + 1) + " time(s).");
retryCount++;
return true;
}
retryCount = 0;
return false;
}
String getResultStatusName(int status) {
String resultName = null;
if (status == 1)
resultName = "SUCCESS";
if (status == 2)
resultName = "FAILURE";
if (status == 3)
resultName = "SKIP";
return resultName;
}
}
}
Here's my console output
[TestNG] Running:
/Users/krmahadevan/Library/Caches/IntelliJIdea2016.3/temp-testng-customsuite.xml
1
Retrying test test with status FAILURE for the 1 time(s).
Test ignored.
1
java.lang.AssertionError: expected [3] but found [1]
Expected :3
Actual :1
<Click to see difference>
at org.testng.Assert.fail(Assert.java:94)
at org.testng.Assert.failNotEquals(Assert.java:513)
at org.testng.Assert.assertEqualsImpl(Assert.java:135)
at org.testng.Assert.assertEquals(Assert.java:116)
at org.testng.Assert.assertEquals(Assert.java:389)
at org.testng.Assert.assertEquals(Assert.java:399)
at com.rationaleemotions.stackoverflow.RetryWithDataProvider.test(RetryWithDataProvider.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:645)
at org.testng.internal.Invoker.retryFailed(Invoker.java:998)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1200)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:756)
at org.testng.TestRunner.run(TestRunner.java:610)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
at org.testng.TestNG.runSuites(TestNG.java:1133)
at org.testng.TestNG.run(TestNG.java:1104)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:127)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
2
Retrying test test with status FAILURE for the 1 time(s).
Test ignored.
2
java.lang.AssertionError: expected [3] but found [2]
Expected :3
Actual :2
<Click to see difference>
at org.testng.Assert.fail(Assert.java:94)
at org.testng.Assert.failNotEquals(Assert.java:513)
at org.testng.Assert.assertEqualsImpl(Assert.java:135)
at org.testng.Assert.assertEquals(Assert.java:116)
at org.testng.Assert.assertEquals(Assert.java:389)
at org.testng.Assert.assertEquals(Assert.java:399)
at com.rationaleemotions.stackoverflow.RetryWithDataProvider.test(RetryWithDataProvider.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:645)
at org.testng.internal.Invoker.retryFailed(Invoker.java:998)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1200)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:756)
at org.testng.TestRunner.run(TestRunner.java:610)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
at org.testng.TestNG.runSuites(TestNG.java:1133)
at org.testng.TestNG.run(TestNG.java:1104)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:127)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
3
===============================================
Default Suite
Total tests run: 5, Failures: 2, Skips: 2
===============================================

Related

TestNG giving NullPointerException [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am validating a method with TestNG and getting the below nullpointer exception.
FAILED: testValidateABC
java.lang.NullPointerException
at packageA.ABCValidator.validateABC(ABCValidator.java:22)
at packageA.ABCValidatorTest.testValidateABC(ABCValidatorTest.java:25)
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.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:774)
at org.testng.TestRunner.run(TestRunner.java:624)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
at org.testng.SuiteRunner.run(SuiteRunner.java:261)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.run(TestNG.java:1048)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
ABCValidatorTest.java (Running this thorugh TestNG to get test results)
public class ABCValidatorTest {
#Test
public void testValidateABC() {
ABCValidator validator = new ABCValidator();
List<String> input = Arrays.asList("0", "1234", "abcd");
List<Boolean> expectedOutput = Arrays.asList(false, true, false);
boolean output;
for (int i = 0; i < input.size(); i++) {
if (StringUtils.isNotEmpty(input.get(i))) {
output = validator.validateABC(input.get(i));
} else {
output = false;
}
Assert.assertEquals((boolean) expectedOutput.get(i), output);
}
}
}
ABCValidator.java (Testing the method present in this class)
public class ABCValidator {
#Autowired(required = false)
private ABCSearch abcRestClient;
public boolean validateABC(String abc_code) {
String response = abcRestClient.searchABCCodes(abc_code);
boolean hasValidabc = true;
if ((response.startsWith("null", 1)) || (response.equals("[]"))) {
hasValidabc = false;
}
return hasValidabc;
}
}
I thought I was getting Nullpointer Exception because some null value was going thorugh, so i handled it in ABCValidatorTest by calling that method only if it is not empty.
EDIT: Updated ABCValidatorTest.java by adding
#ContextConfiguration(classes = {ABCValidator.class})
Getting the below error now:
org.testng.TestNGException: java.net.UnknownHostException: testng.org
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:320)
If you want to use spring dependency injection (#Autowired) you should run your tests with spring context.
#ContextConfiguration(classes = {classes you want to use})
If spring boot should annotate your test class with
#SpringBootTest(classes = {classes you want to use})

Java - JUnit how to do?

I have the following method and how can I do the JUnit testing on it?
Parser is my constructor, which I am also using as my return type of my following method.
As this method is splitting the string in three one, so for that I want to write a unit test case.
I am somehow familiar with JUnit but not that much. Any guidance/ link/ help will be appreciated.
public class Example {
public Parser thirdValueCleanup(String value) {
String thirdValueValue = value.trim();
System.out.println("TestData: "+thirdValueValue);
String firstValueRegex = "[A-z]\\d[A-z]";
String secondValueRegex = "\\d[A-z]\\d";
String thirdValueRegex = "[SK|sk]{2}";
Pattern firstValuePattern = Pattern.compile(".*\\W*("+firstValueRegex+")\\W*.*");
Pattern secondValuePattern = Pattern.compile(".*\\W*("+secondValueRegex+")\\W*.*");
Pattern thirdValuePattern = Pattern.compile(".*\\W*("+thirdValueRegex+")\\W*.*");
String firstValue = "";
String secondValue = "";
String thirdValue = "";
Matcher firstValueMatcher = firstValuePattern.matcher(thirdValueValue);
if(firstValueMatcher.matches()) {
firstValue = firstValueMatcher.group(1);
}
Matcher secondValueMatcher = secondValuePattern.matcher(thirdValueValue);
if(secondValueMatcher.matches()) {
secondValue = secondValueMatcher.group(1);
}
Matcher thirdValueMatcher = thirdValuePattern.matcher(thirdValueValue);
if(thirdValueMatcher.matches()) {
thirdValue = thirdValueMatcher.group(1);
}
String FirstValueName = firstValue + " " + secondValue;
String thirdValueName = thirdValue;
return new Parser(FirstValueName, thirdValueName);
}
public Parser(String firstValue, String secondValue) {
this.firstValue = firstValue;
this.secondValue = secondValue;
}
public String getFirstValue() {
return firstValue;
}
public String getSecondValue() {
return secondValue;
}
}
I tried in my test:
public final void testThirdValueCleanup() {
System.out.println("retrieve");
String factories = "SK S6V 7L4";
Parser parser = new Parser();
Parser expResult = SK S6V 7L4;
Parser result = parser.thirdValueCleanup(factories);
assertEquals(expResult, result);
}
I got this error:
junit.framework.AssertionFailedError: expected:<SK S6V 7L4> but was:<com.example.Parser#379619aa>
at junit.framework.Assert.fail(Assert.java:57)
at junit.framework.Assert.failNotEquals(Assert.java:329)
at junit.framework.Assert.assertEquals(Assert.java:78)
at junit.framework.Assert.assertEquals(Assert.java:86)
at junit.framework.TestCase.assertEquals(TestCase.java:253)
at com.example.ParserTest.testthirdValueCleanup(ParserTest.java:29)
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 junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:252)
at junit.framework.TestSuite.run(TestSuite.java:247)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
try this
#Test
public final void testThirdValue() {
System.out.println("retrieve");
String factories = " BK M6B 7A4";
Parser parser = new Parser();
Parser province = parser.thirdValue(factories);
assertEquals("M6B 7A4", province.getFirstValue());
assertEquals("BK", province.getSecondValue());
}
Any guidance/ link/ help will be appreciated. thanks
As a simple approach, you might want to try out something within the following lines. As a first step create the test class:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ExampleTest {
Example example = new Example();
#Test
public void testThirdValueCleanup(){
//pass some inputs to your function
//by exclicitly calling
//example.thirdValueCleanup(input params...);
//a simple test case would be to check if it you get what your expect
Parser expected = new Parser("set this one as it should be");
assertEquals(example.thirdValueCleanup(some inputs...), expected);
}
/*
* Here you can define more test cases
*/
}
Next you can create a class to run your test:
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(ExampleTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
For more information you can consult either this tutorial or getting started by JUnit.

EasyMock unexpected method call

I can't work out how to setup the expectation of a call to a mock class. Here is the JUnit test:
public class AfkTest extends TestCase {
private AfkPlayerManager manager;
private Player player;
private Set<AfkPlayer> afkPlayers;
public void setUp() throws Exception {
super.setUp();
manager = new AfkPlayerManager();
player = EasyMock.createMock(Player.class);
afkPlayers = new HashSet<AfkPlayer>();
}
public void tearDown() {
}
public void testNotifyOfAfkPlayerSuccess() {
AfkPlayer afkPlayer = new AfkPlayer();
afkPlayer.setPlayer(player);
afkPlayer.setReason("TEST REASON");
afkPlayers.add(afkPlayer);
List<Player> onlinePlayers = new ArrayList<Player>();
onlinePlayers.add(player);
onlinePlayers.add(player);
EasyMock.expect(player.getDisplayName()).andReturn("TEST PLAYER");
player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]");
EasyMock.expectLastCall().times(1);
//activate the mock
EasyMock.replay(player);
assertTrue(manager.notifyOfAfkPlayer(onlinePlayers, afkPlayer));
//verify call to sendMessage is made or not
EasyMock.verify(player);
}
}
And the method that I am testing:
public class AfkPlayerManager implements Manager {
public boolean notifyOfAfkPlayer(Collection<Player> onlinePlayers, AfkPlayer afkPlayer) {
if (afkPlayer == null) {
return false;
}
String message = ChatColor.BLUE + afkPlayer.getPlayer().getDisplayName();
message += ChatColor.AQUA + " is AFK.";
if (afkPlayer.getReason().length() > 0) {
message += " [" + afkPlayer.getReason() + "]";
}
if (onlinePlayers != null && onlinePlayers.size() > 1) {
int notified = 0;
for (Player onlinePlayer : onlinePlayers) {
onlinePlayer.sendMessage(message);
notified++;
}
if (notified > 0) {
return true;
}
}
return false;
}
}
Why is this giving me the AssertionError:
java.lang.AssertionError: Unexpected method call
Player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]"):
Player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]"): expected: 1, actual: 0 at
org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at
org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at com.sun.proxy.$Proxy3.sendMessage(Unknown Source) at
crm.afk.AfkPlayerManager.notifyOfAfkPlayer(AfkPlayerManager.java:33)
at crm.test.AfkTest.testNotifyOfAfkPlayerSuccess(AfkTest.java:84) 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
junit.framework.TestCase.runTest(TestCase.java:176) at
junit.framework.TestCase.runBare(TestCase.java:141) at
junit.framework.TestResult$1.protect(TestResult.java:122) at
junit.framework.TestResult.runProtected(TestResult.java:142) at
junit.framework.TestResult.run(TestResult.java:125) at
junit.framework.TestCase.run(TestCase.java:129) at
junit.framework.TestSuite.runTest(TestSuite.java:252) at
junit.framework.TestSuite.run(TestSuite.java:247) at
org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
The expected and actual are different.
Expected: §9TEST PLAYER§b is AFK. [TEST REASON]
Actual: §9TEST PLAYER§b is AFK. [TEST REASON]
The  at the beginning is missing. So it fails as it should.

Basic JUNIT testing. I am getting java.lang.AssertionError

I am new to JUNIT testing but tried a lot to test the class UserProfileService. Please help or suggest possible errors I am doing:
#Path("/update")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response updateProfile(final PartyProfile partyProfile) {
final ProxyResponse response = new ProxyResponse();
try {
final boolean isUpdated = partyProfileDao.updateProfile(partyProfile);
if (isUpdated) {
LOGGER.info("update Request completed successfully");
setSuccessResponse(response, "Request completed successfully");
try{
final String trailId = partyProfileDao.fetchPartyTrial(partyProfile.getPartyId());
activityPush(trailId, partyProfile.getPartyId());
}catch(Exception ex){
ex.printStackTrace();
LOGGER.error("Exception while triggering segmentation++");
}
} else {
LOGGER.info("Unable to update profile");
setErrorResponse(response, "PRFUPDT500", "Unable to update profile");
return Response.ok(response).header("valid", FLAG_FALSE).build();
}
} catch (Exception exc) {
LOGGER.error("Unable to update profile:" + exc.getMessage());
setInternalErrorResponse(exc, response, "Unable to update profile");
return Response.ok(response).header("valid", FLAG_FALSE).build();
}
return Response.ok(response).build();
}
I have written following JUNIT test:
public class PartyProfileServiceTest {
private PartyProfileDAO partyDAO;
private PartyProfileService partyService;
#Before
public void setUp() throws Exception {
partyDAO = EasyMock.createMock(PartyProfileDAO.class);
partyService = EasyMock.createMock(PartyProfileService.class);
partyService.setUserProfileDAO(partyDAO);
}
#Test
public void testUpdateValidProfile() throws Exception {
System.out.println("inside junit");
PartyProfile partyProfile = new PartyProfile();
partyProfile.setFirstName("adsfsdfg");
partyProfile.setAddress("adressabc");
partyProfile.setPartyId("dfdf");
partyProfile.getSalutation();
partyProfile.setMiddleName("asfsaf");
partyProfile.setLastName("easdsddff");
partyProfile.setNickName("srb");
partyProfile.setGender("m");
partyProfile.setUpdateDate("sdd");
partyProfile.setEducation("srg");
partyProfile.setInsurance("sg");
partyProfile.setState("sdfg");
partyProfile.setSiteId("fdg");
partyProfile.setRandomNo("feddg");
partyProfile.setPartyId("56666");
EasyMock.expect(partyDAO.updateProfile(partyProfile)).andReturn(true);
EasyMock.expect(partyDAO.fetchPartyTrial("validPartyId")).andReturn("pass");
EasyMock.replay(partyDAO);
EasyMock.expect(partyService.activityPush("pass", "validPartyId")).andReturn(true);
EasyMock.replay(partyService);
Response response = partyService.updateProfile(partyProfile);
ProxyResponse proxyResponse = (ProxyResponse) response.getEntity();
Assert.assertSame("Unable to update profile", proxyResponse.getData().get("message"));
}
}
Error:
java.lang.AssertionError:
Unexpected method call PartyProfileService.updateProfile(com.cts.vcoach.proxy.model.PartyProfile#11e170c):
PartyProfileService.setUserProfileDAO(EasyMock for class com.cts.vcoach.proxy.dao.PartyProfileDAO): expected: 1, actual: 0
PartyProfileService.activityPush("pass", "validPartyId"): expected: 1, actual: 0
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:97)
at com.cts.vcoach.proxy.service.rest.PartyProfileService$$EnhancerByCGLIB$$46a1112f.updateProfile(<generated>)
at com.cts.vcoach.proxy.service.rest.PartyProfileServiceTest.testUpdateValidProfile(PartyProfileServiceTest.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:44)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
You're trying to test the class PartyProfileService. So you should create an instance of this class, and call its methods in your test. But that's not what you're doing. You're creating a mock instance of this class:
partyService = EasyMock.createMock(PartyProfileService.class);
Replace this line by
partyService = new PartyProfileService();
If you need to partially mock the service, i.e. mock the method activityPush(), but not the other ethods, then see the documentation for how to do that:
ToMock mock = createMockBuilder(ToMock.class)
.addMockedMethod("mockedMethod")
.createMock();

Hibernate JPA delete entity with cascade (deleted entity passed to persist)

I have searched for and read/studied almost every link on the web concerning problems with deleting parent entities and having the delete cascade through my OneToMany collections. I have tried many of the suggestions, including removing all references to the contained collection, different Cascade type combinations, etc. Still when I try to delete a parent entity, I continually get an exception on persisting a deleted entity.
I have an Adhesive entity class which contains a OneToMany relationship with AdhesiveChemicals like this:
#Entity
#Table(name = "Adhesive")
#NamedQueries({
public class Adhesive implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
private Long adhesiveId;
private String adhesiveName;
private String costPerDryPound;
private String solidPercent;
private String totalActCost;
private String totalDry;
private String totalWet;
private Boolean inactive;
private List<AdhesiveChemicals> adhesiveChemicals;
private List<AdhesiveComponent> adhesiveComponentsList;
#OneToMany(cascade= {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.REFRESH}, mappedBy="adhesive", targetEntity=AdhesiveChemicals.class, orphanRemoval=true)
#LazyCollection(LazyCollectionOption.FALSE)
public List<AdhesiveChemicals> getAdhesiveChemicalsList() {
return adhesiveChemicals;
}
public void setAdhesiveChemicalsList(List<AdhesiveChemicals> adhesiveChemicals) {
this.adhesiveChemicals = adhesiveChemicals;
}
#OneToMany(mappedBy="adhesive", targetEntity=AdhesiveComponent.class)
#LazyCollection(LazyCollectionOption.FALSE)
public List<AdhesiveComponent> getAdhesiveComponentsList() {
return adhesiveComponentsList;
}
public void setAdhesiveComponentsList(List<AdhesiveComponent> adhesiveComponentsList) {
this.adhesiveComponentsList = adhesiveComponentsList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (adhesiveId != null ? adhesiveId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Adhesive)) {
return false;
}
Adhesive other = (Adhesive) object;
if ((this.adhesiveId == null && other.adhesiveId != null) || (this.adhesiveId != null && !this.adhesiveId.equals(other.adhesiveId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Adhesive{" + "adhesiveId=" + adhesiveId + ", adhesiveName=" + adhesiveName +
", costPerDryPound=" + costPerDryPound + ", solidPercent=" + solidPercent +
", totalActCost=" + totalActCost + ", totalDry=" + totalDry + ", totalWet=" +
totalWet + ", inactive=" + inactive + '}';
}
}
The AdhesiveChemicals class:
#Entity
public class AdhesiveChemicals implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String wetLbs;
private String dryLbs;
private String actualCost;
private Adhesive adhesive;
private Chemical chemical;
#ManyToOne(fetch= FetchType.EAGER, optional=false)
#JoinColumn(name="adhesive_id")
public Adhesive getAdhesive() {
return adhesive;
}
public void setAdhesive(Adhesive adhesive) {
this.adhesive = adhesive;
}
#ManyToOne(fetch = FetchType.EAGER, optional=false)
#JoinColumn(name="chemical_id")
public Chemical getChemical() {
return chemical;
}
public void setChemical(Chemical chemical) {
this.chemical = chemical;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof AdhesiveChemicals)) {
return false;
}
AdhesiveChemicals other = (AdhesiveChemicals) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "AdhesiveChemicals{" + "wetLbs=" + wetLbs + ", dryLbs=" + dryLbs
+ ", actualCost=" + actualCost + ", adhesive=" + adhesive + ", chemical=" + chemical + '}';
}
The code that is called to delete the Adhesive is here:
// Handler for Button[fx:id="pricingAdhesiveDeleteButton"] onMouseClicked
public void doAdhesiveDelete(MouseEvent event) {
// handle the event here
logger.info("Entering {}.doAdhesiveDelete.", this.getClass().getName());
if (pricingAdhesiveTable.getSelectionModel().getSelectedIndex() < 0) {
return;
}
DialogFX dialog = new DialogFX(DialogFX.Type.QUESTION);
dialog.setTitleText("Delete?");
dialog.setMessage(" Do you really wish to delete " + tempAdhesive.getAdhesive() + "? ");
if (dialog.showDialog() == 1) {
return;
}
tempAdhesive.getAdhesiveChemicalsList().clear();
pricingAdhesiveTableList.remove(tempAdhesive);
// for (AdhesiveChemicals adhesiveChemicals : acList) {
// costingService.removeAdhesiveChemicals(adhesiveChemicals.getId());
// }
costingService.removeAdhesive(tempAdhesive.getId());
init();
pricingAdhesiveDeleteButton.setDisable(true);
}
The costingService is a Glassfish service which has implementations of all of the create/update/delete methods on the database. The removeAdhesive method looks like this:
#Service
#Transactional(readOnly=false)
public class CostingServiceImpl implements CostingService {
private static final Logger logger = LoggerFactory.getLogger(CostingServiceImpl.class.getName());
private EntityManager em;
#PersistenceContext(name="LamtecVoyagerPU")
public void setEntityManager(EntityManager entityManager) {
this.em = entityManager;
}
#Override
public void removeAdhesive(Long Id) {
logger.info("Entering {}.removeAdhesive.", this.getClass().getName());
Adhesive a = em.find(Adhesive.class, Id);
// a.getAdhesiveChemicalsList().clear();
em.remove(a);
}
As you can see, at this point I have cascading limited to REFRESH, MERGE and REMOVE on the one to many relationship and I have orphan removal set to true. However, when I try to delete an adhesive which contains some AdhesiveChemicals, the following exception is thrown. (There is some extra stuff in there that has to do with the communication between the client and the server.)
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1440)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:69)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:33)
at javafx.event.Event.fireEvent(Event.java:171)
at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3113)
at javafx.scene.Scene$ClickGenerator.access$8600(Scene.java:3051)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3333)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3164)
at javafx.scene.Scene$MouseHandler.access$1900(Scene.java:3119)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1559)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2261)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:228)
at com.sun.glass.ui.View.handleMouseEvent(View.java:528)
at com.sun.glass.ui.View.notifyMouse(View.java:922)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
at com.sun.glass.ui.win.WinApplication$2$1.run(WinApplication.java:67)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1435)
... 31 more
Caused by: org.springframework.transaction.UnexpectedRollbackException: JTA transaction unexpectedly rolled back (maybe due to a timeout); nested exception is javax.transaction.RollbackException: Transaction marked for rollback.
at org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:1012)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy463.removeAdhesive(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.remoting.support.RemoteInvocationTraceInterceptor.invoke(RemoteInvocationTraceInterceptor.java:77)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy464.removeAdhesive(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.remoting.support.RemoteInvocation.invoke(RemoteInvocation.java:205)
at org.springframework.remoting.support.DefaultRemoteInvocationExecutor.invoke(DefaultRemoteInvocationExecutor.java:38)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invoke(RemoteInvocationBasedExporter.java:78)
at org.springframework.remoting.support.RemoteInvocationBasedExporter.invokeAndCreateResult(RemoteInvocationBasedExporter.java:114)
at org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter.handleRequest(HttpInvokerServiceExporter.java:73)
at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:49)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:585)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
at org.springframework.remoting.support.RemoteInvocationUtils.fillInClientStackTraceIfPossible(RemoteInvocationUtils.java:47)
at org.springframework.remoting.support.RemoteInvocationResult.recreate(RemoteInvocationResult.java:115)
at org.springframework.remoting.support.RemoteInvocationBasedAccessor.recreateRemoteInvocationResult(RemoteInvocationBasedAccessor.java:85)
at org.springframework.remoting.httpinvoker.HttpInvokerClientInterceptor.invoke(HttpInvokerClientInterceptor.java:148)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy14.removeAdhesive(Unknown Source)
at com.lamtec.pricingclient.PricingPresenter.doAdhesiveDelete(PricingPresenter.java:982)
... 36 more
Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:473)
at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:855)
at com.sun.enterprise.transaction.UserTransactionImpl.commit(UserTransactionImpl.java:208)
at org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:1009)
... 102 more
Caused by: javax.persistence.EntityNotFoundException: deleted entity passed to persist: [com.lamtec.lamteccommon.data.costing.AdhesiveChemicals#<null>]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1369)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1315)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1321)
at org.hibernate.ejb.AbstractEntityManagerImpl$3.mapManagedFlushFailure(AbstractEntityManagerImpl.java:1235)
at org.hibernate.transaction.synchronization.CallbackCoordinator.beforeCompletion(CallbackCoordinator.java:122)
at org.hibernate.transaction.synchronization.HibernateSynchronizationImpl.beforeCompletion(HibernateSynchronizationImpl.java:51)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:435)
... 105 more
The original query which populates the list containing Adhesives (and by default due to eager fetching, the AdhesiveChemicals):
#Override
public List<Adhesive> listAdhesives() {
logger.info("Entering {}.listAdhesives.", this.getClass().getName());
Query query = em.createNamedQuery("Adhesive.findAll");
List<Adhesive> result = new ArrayList<>();
try {
result = query.getResultList();
} catch (Exception ex) {
logger.info("Not able to get Adhesive list");
throw ex;
}
return result;
}
The results of this are placed in the pricingAdhesiveTableList. When I try to remove the adhesive to be deleted, I remove it from the pricingAdhesiveTableList also, as can be seen in the doAdhesiveDelete code above.
Please don't worry about my feelings. I have already beaten myself up pretty good over this one. I have many other deletes that are working fine, but this one continues to perplex me. If you need any more information, please let me know.
Oh, the database is MS SQL Server and I'm using Hibernate 3.6 for my JPA provider. Glassfish is version 3.X.
Thanks.

Categories