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

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.

Related

How to avoid Transaction was marked for rollback only; cannot commit in async task

I has develop API for integrate file in database in async task.
I want my entire file processed, and I record every error in the database.
My API call this Service
#Service
public class ImportFichier {
#Async("taskExecutor")
public void importReference(ImportFichierDTO importFichierDTO,
List<Reference> references,
Long idEntite,
Long currentUserId,
boolean update){
log.debug("Request to importReference pour entite : {}", idEntite);
for(Reference reference : references) {
if (update) {
referentielService.update(idEntite, reference, currentUserId, importFichierDTO.getId());
} else {
referentielService.add(idEntite, reference, currentUserId, importFichierDTO.getId());
}
}
// mise à jour de l'heure de fin du traitement d'import
importFichierDTO.setDateFin(ZonedDateTime.now());
importFichierService.save(importFichierDTO);
return;
}
For adding data, treatment call this service :
#Service
#Transactional
public class ReferentielCompteurServiceImpl implements ReferentielCompteurService {
....
#Override
#Transactional(noRollbackFor = {CustomException.class, ConstraintViolationException.class})
public Compteur add(Compteur compteur, Long entiteMereId, Long entiteId, Long userId, Long importId) {
Optional<ArticleEtat> articleEtat = articleEtatRepository.findOneByCode(compteur.getCodeEtat());
if (!articleEtat.isPresent()) {
if (importId > 0) {
importFichierTraceService.add(importId, compteur.getUuidReference().toString(), CustomError.ERROR_ARTICLE_ETAT_NOT_FOUND.getErrorDescription());
return compteur;
} else {
throw new CustomException(CustomError.ERROR_ARTICLE_ETAT_NOT_FOUND);
}
}
....
ReferentielCompteurDTO result = save(referentielCompteurDTO, importId);
And method "save" in the same service :
#Override
#Transactional(noRollbackFor = {CustomException.class, ConstraintViolationException.class})
public ReferentielCompteurDTO save(ReferentielCompteurDTO referentielCompteurDTO, Long importId) {
log.debug("Request to save ReferentielCompteur : {}", referentielCompteurDTO);
if (referentielCompteurDTO.getDateCreation() == null) {
referentielCompteurDTO.setDateCreation(ZonedDateTime.now());
}
referentielCompteurDTO.setDateModification(ZonedDateTime.now());
ReferentielCompteur referentielCompteur = referentielCompteurMapper.toEntity(referentielCompteurDTO);
try {
referentielCompteur = referentielCompteurRepository.save(referentielCompteur);
} catch (ConstraintViolationException cve) {
importFichierTraceService.add(importId, referentielCompteurDTO.getReferenceId().toString(), cve.getMessage());
}
return referentielCompteurMapper.toDto(referentielCompteur);
}
When I generate a ConstraintViolationException I have this exception :
Transaction was marked for rollback only; cannot commit' and exception = 'Transaction was marked for rollback only; cannot commit; nested exception is org.hibernate.TransactionException: Transaction was marked for rollback only; cannot commit'
org.springframework.orm.jpa.JpaSystemException: Transaction was marked for rollback only; cannot commit; nested exception is org.hibernate.TransactionException: Transaction was marked for rollback only; cannot commit
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:312)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:223)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:540)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:532)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:304)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
I see several post, but I don't understand how solve this problem, and is it possible
Can you help me please?
Following the advice of M.Deinum, I try :
for importFichierTraceService.add
#Transactional(propagation = REQUIRES_NEW)
public void add(Long importId, String line, String message) {
I delete #Transactional and catch Exception
#Override
public ReferentielCompteurDTO save(ReferentielCompteurDTO referentielCompteurDTO, Long importId) {
And add catch Exception in :
#Override
public Compteur add(Compteur compteur, Long entiteMereId, Long entiteId, Long userId, Long importId) {
try {
result = save(referentielCompteurDTO, importId);
} catch (ConstraintViolationException cve) {
importFichierTraceService.add(importId, referentielCompteurDTO.getReferenceId().toString(), cve.getMessage());
return compteur;
}
Result is the same

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.

Vaadin with Grails Database error

I am using vaadin7 with grails i have created model and service and trying to access it when click on login button to check login details.
I search a lot but no relevant result, i am new to grails framework.
i am getting below error when trying to access service class:-
java.lang.NullPointerException
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130)
at org.codehaus.groovy.grails.orm.support.GrailsTransactionTemplate.execute(GrailsTransactionTemplate.groovy:85)
at com.xfuel.web.services.PeopleService.checkLogin(PeopleService.groovy)
at com.xfuel.web.services.PeopleService$checkLogin.call(Unknown Source)
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:120)
at test.Test$2.buttonClick(Test.groovy:60)
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.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:508)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:198)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:161)
at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:984)
at com.vaadin.ui.Button.fireClick(Button.java:393)
at com.vaadin.ui.Button$1.click(Button.java:57)
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)
My Vaadincode is below :-
class Test extends UI {
public Test() {
// TODO Auto-generated constructor stub
}
#Override
protected void init(VaadinRequest request) {
HorizontalLayout fields = new HorizontalLayout();
fields.setSpacing(true);
fields.setMargin(true);
fields.addStyleName("fields");
final TextField username = new TextField("Username");
username.focus();
fields.addComponent(username);
final PasswordField password = new PasswordField("Password");
fields.addComponent(password);
final Button signin = new Button("Sign In");
signin.addStyleName("default");
fields.addComponent(signin);
fields.setComponentAlignment(signin, Alignment.BOTTOM_LEFT);
final ShortcutListener enter = new ShortcutListener("Sign In",
KeyCode.ENTER, null) {
#Override
public void handleAction(Object sender, Object target) {
signin.click();
}
};
signin.addClickListener(new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
if (username.getValue() != null
&& username.getValue().equals("")
&& password.getValue() != null
&& password.getValue().equals("")) {
signin.removeShortcutListener(enter);
PeopleService p1 = new PeopleService();
p1.checkLogin("", "");
// iPeopleService.checkLogin(username.getValue(), password.getValue());
buildMainView();
} else {
}
}
});
signin.addShortcutListener(enter);
setContent(fields);
}
}
And domain class :-
class People {
String name;
String apppassword;
static constraints = {
}
}
and Grails services code :-
#Transactional
class PeopleService {
def serviceMethod() {
}
public People checkLogin(String username, String password) {
def query = People.where{
peopleID == username &&
apppassword == password &&
visible == true
}
return people = query.find()
}
i below is the datasource :-
development {
dataSource {
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/sample"
username = "root"
password = "root"
loggingSql = true
}
}
i did not understand the reason of this error. Can someone please help me?
Thanks

Cloning entity in playframework

I have problem with cloning entity in my application created with play framework 2.1.
When I'm runing method below I get RollbackException: Error while committing the transaction.
My question is: What is a proper way to clone entity using jpa in playframework?
#play.db.jpa.Transactional
public static Result edit(final Long id) {
final Client client = Client.findById(id);
if (client == null) {
return notFound(String.format("Client %s does not exist.", id));
}
if(client.address.id == client.corrAddress.id){
client.corrAddress = client.address.clone();
}
Form<Client> filledForm = CLIENT_FORM.fill(client);
return ok(form.render(filledForm, "Edycja danych klienta"));
}
Address clone method:
public Address clone(){
return new Address(this.street, this.postCode, this.city);
}
UPDATE:
I made some changes in code. I don't use method clone now, as #Christopher Hunt suggested.
I also got another error.
I made method cascade in Client class:
public void cascade(){
if(address.equals(corrAddress)){
if(address.id != null && corrAddress.id != null
&& address.id.equals(corrAddress.id)){
address.client = this;
address.corrClient = this;
address.saveOrUpdate();
corrAddress = null;
} else {
address.client = this;
address.corrClient = this;
address.saveOrUpdate();
corrAddress = null;
}
} else {
if(address.id != null && corrAddress.id != null
&& address.id.equals(corrAddress.id)){
System.out.println("TEST");
address.client = this;
address.corrClient = null;
address.saveOrUpdate();
String street = this.corrAddress.street;
String postCode = this.corrAddress.postCode;
String city = this.corrAddress.city;
corrAddress = null;
/** CODE BELOW CAUSES ERROR: **/
corrAddress = new Address(street, postCode, city);
corrAddress.client = null;
corrAddress.corrClient = this;
corrAddress.saveOrUpdate();
/** CODE ABOVE CAUSES ERROR: **/
} else {
address.client = this;
address.saveOrUpdate();
corrAddress.corrClient = this;
corrAddress.saveOrUpdate();
}
}
}
definition of address references in Client class:
#Valid
#OneToOne(mappedBy="client", orphanRemoval=true, fetch = FetchType.EAGER)
public Address address;
#Valid
#OneToOne(mappedBy="corrClient", orphanRemoval=true, fetch = FetchType.EAGER)
public Address corrAddress;
Now I'm getting error:
play.api.Application$$anon$1: Execution
exception[[PersistenceException: org.hibernate.HibernateException:
More than one row with the given identifier was found: 2, for class:
models.Address]] at
play.api.Application$class.handleError(Application.scala:289)
~[play_2.10.jar:2.1.0] at
play.api.DefaultApplication.handleError(Application.scala:383)
[play_2.10.jar:2.1.0] at
play.core.server.netty.PlayDefaultUpstreamHandler$$anon$2$$anonfun$handle$1.apply(PlayDefaultUpstreamHandler.scala:132)
[play_2.10.jar:2.1.0] at
play.core.server.netty.PlayDefaultUpstreamHandler$$anon$2$$anonfun$handle$1.apply(PlayDefaultUpstreamHandler.scala:128)
[play_2.10.jar:2.1.0] at
play.api.libs.concurrent.PlayPromise$$anonfun$extend1$1.apply(Promise.scala:113)
[play_2.10.jar:2.1.0] at
play.api.libs.concurrent.PlayPromise$$anonfun$extend1$1.apply(Promise.scala:113)
[play_2.10.jar:2.1.0] javax.persistence.PersistenceException:
org.hibernate.HibernateException: More than one row with the given
identifier was found: 2, for class: models.Address at
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1360)
~[hibernate-entitymanager-4.1.1.Final.jar:4.1.1.Final] at
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1288)
~[hibernate-entitymanager-4.1.1.Final.jar:4.1.1.Final] at
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1294)
~[hibernate-entitymanager-4.1.1.Final.jar:4.1.1.Final] at
org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:877)
~[hibernate-entitymanager-4.1.1.Final.jar:4.1.1.Final] at
models.clients.Client.update(Client.java:58) ~[na:na] at
models.clients.Client.saveOrUpdate(Client.java:110) ~[na:na] Caused
by: org.hibernate.HibernateException: More than one row with the given
identifier was found: 2, for class: models.Address at
org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:104)
~[hibernate-core-4.1.1.Final.jar:4.1.1.Final] at
org.hibernate.loader.entity.EntityLoader.loadByUniqueKey(EntityLoader.java:161)
~[hibernate-core-4.1.1.Final.jar:4.1.1.Final] at
org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:2209)
~[hibernate-core-4.1.1.Final.jar:4.1.1.Final] at
org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:661)
~[hibernate-core-4.1.1.Final.jar:4.1.1.Final] at
org.hibernate.type.EntityType.resolve(EntityType.java:441)
~[hibernate-core-4.1.1.Final.jar:4.1.1.Final] at
org.hibernate.type.EntityType.replace(EntityType.java:298)
~[hibernate-core-4.1.1.Final.jar:4.1.1.Final]
Important is that I don't want to operate with 2 element list. I want 2 fileds (address, corrAddress) in my Client class.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

I am using struts and hibernate. I have a parent and child relation using set in hbm.
In the action I am using session.saveOrUpdate() method to save but while saving it is showing the below error. Can anyone help regardng this with explanation where I made the mistake?
Here is my hbm.file
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.model.cargo" table="cargo">
<id name="id" column="id" type="java.lang.Long">
<generator class="increment" />
</id>
<property name="cname" column="cname" />
<property name="cdate" column="cdate" />
<property name="csource" column="csource" />
<property name="cdestination" column="cdestination" />
<property name="create" column="createby" />
<property name="status" column="status" />
<set name="itemList" table="item" inverse="true"
cascade="all-delete-orphan">
<key>
<column name="id" />
</key>
<one-to-many class="com.model.Item" />
</set>
</class>
<class name="com.model.Item" table="item">
<id name="itemid" column="itemid" type="java.lang.Long">
<generator class="increment" />
</id>
<property name="itemName" column="itemname" />
<property name="weight" column="weight" />
<many-to-one class="com.model.cargo" name="cargo"
column="id" />
</class>
</hibernate-mapping>
My action
package com.action;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.plugin.HibernatePlugIn;
import com.form.cargoForm;
import com.model.cargo;
import com.model.Item;
public class CargoAction extends DispatchAction {
public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("Entering Master add method");
}
try {
cargoForm cargoForm = (cargoForm) form;
//System.out.println("ID" + cargoForm.getId());
cargo cargo = new cargo();
System.out.println("in cargo Action");
// copy customerform to model
cargoForm.reset(mapping, request);
BeanUtils.copyProperties(cargo, cargoForm);
cargoForm.reset(mapping, request);
// cargoForm.setInputParam("new");
// updateFormBean(mapping, request, cargoForm);
}
catch (Exception ex) {
ex.printStackTrace();
return mapping.findForward("failure");
}
return mapping.findForward("success1");
}
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
SessionFactory sessionFactory=null;
Session session =null;
System.out.println("in cargo Action");
try{
sessionFactory = (SessionFactory) servlet
.getServletContext().getAttribute(HibernatePlugIn.KEY_NAME);
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
cargoForm carForm = (cargoForm) form;
cargo cargo = new cargo();
System.out.println("in cargo Action");
BeanUtils.copyProperties(cargo,carForm);
System.out.println("id"+ carForm.getId());
System.out.println("item id"+ carForm.getItemid());
Set itemset = carForm.getItemDtl();
System.out.println("size"+itemset.size());
Iterator iterator =itemset.iterator();
while(iterator.hasNext()) {
Item it = (Item)iterator.next();
System.out.println("name"+it.getItemName()); //log.debug("HERE");
it.setCargo(cargo); }
cargo.setItemList(itemset);
System.out.println("size"+ itemset.size());
session.saveOrUpdate("cargo",cargo);
tx.commit();
}catch(Exception e){
e.printStackTrace();
}
return mapping.findForward("success");
}
public ActionForward search(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("in cargo search Action");
SessionFactory sessionFactory = (SessionFactory) servlet
.getServletContext().getAttribute(HibernatePlugIn.KEY_NAME);
HttpSession session1 = request.getSession();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
cargoForm cargoform = (cargoForm) form;
// System.out.println("Name"+cargoForm.getName());
cargo cargo = new cargo();
System.out.println("in cargo search Action");
// copy customerform to model
BeanUtils.copyProperties(cargo, cargoform);
String name;
String status;
String createby;
name = cargo.getCname();
status = cargo.getStatus();
createby = cargo.getCreate();
System.out.println("Name..." + name);
System.out.println("status..." + status);
System.out.println("createby..." + createby);
try {
if ((name.equals("")) && (createby.equals(""))
&& (status.equals("")))
return mapping.findForward("failure");
String SQL_QUERY = "from cargo c where c.cname=:name or c.status=:status or c.create=:createby";
Query query = session.createQuery(SQL_QUERY);
query.setParameter("name", name);
query.setParameter("status", status);
query.setParameter("createby", createby);
ArrayList al = new ArrayList();
for (Iterator i = query.iterate(); i.hasNext();) {
cargo cargo1 = (cargo) i.next();
al.add(cargo1);
System.out.println("Cargo ID is:" + cargo1.getId());
}
System.out.println("Cargo list is:" + al.size());
session1.setAttribute("clist", al);
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("failure");
}
System.out.println("search Cargo list is success");
return mapping.findForward("success");
}
public ActionForward edit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
SessionFactory sessionFactory=null;
Session session =null;
if (log.isDebugEnabled()) {
log.debug("Entering Master Edit method");
}
try {
sessionFactory = (SessionFactory) servlet
.getServletContext().getAttribute(HibernatePlugIn.KEY_NAME);
session = sessionFactory.openSession();
Transaction transaction=session.beginTransaction();
cargoForm carForm = (cargoForm) form;
// System.out.println(carForm.getStatus());
// System.out.println(carForm.getCreate());
cargo cargo = new cargo();
BeanUtils.copyProperties(cargo, carForm);
System.out.println("In Cargo Edit "+cargo.getId());
String qstring = "from cargo c where c.id=:id";
Query query = session.createQuery(qstring);
query.setParameter("id", cargo.getId());
ArrayList all = new ArrayList();
cargo c = (cargo) query.iterate().next();
System.out.println("Edit Cargo list " + all.size());
Set purchaseArray = new HashSet();
System.out.println("Edit"+c.getItemList().size());
carForm.setItemDtl(purchaseArray);
BeanUtils.copyProperties(carForm,c);
// transaction.commit();
session.flush();
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("failure");
}
// return a forward to edit forward
System.out.println("Edit Cargo list is success");
return mapping.findForward("succ");
}
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
try {
SessionFactory sessionFactory = (SessionFactory) servlet
.getServletContext().getAttribute(HibernatePlugIn.KEY_NAME);
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
cargoForm carForm = (cargoForm) form;
// System.out.println(carForm.getStatus());
// System.out.println(carForm.getCreate());
cargo cargo = new cargo();
BeanUtils.copyProperties(cargo, carForm);
System.out.println("In Cargo Delete "+cargo.getId());
//String qstring = "delete from cargo c where c.id=:id";
//Query query = session.createQuery(qstring);
session.delete("cargo",cargo);
// session.delete(cargo);
// session.flush();
//query.setParameter("id", cargo.getId());
//int row=query.executeUpdate();
//System.out.println("deleted row"+row);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("failure");
}
// return a forward to edit forward
System.out.println("Deleted success");
return mapping.findForward("succes");
}
}
My parent model
package com.model;
import java.util.HashSet;
import java.util.Set;
public class cargo {
private Long id;
private String cname;
private String cdate;
private String csource;
private String cdestination;
private String create;
private String status;
private Set itemList = new HashSet();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCdate() {
return cdate;
}
public void setCdate(String cdate) {
this.cdate = cdate;
}
public String getCsource() {
return csource;
}
public void setCsource(String csource) {
this.csource = csource;
}
public String getCdestination() {
return cdestination;
}
public void setCdestination(String cdestination) {
this.cdestination = cdestination;
}
public String getCreate() {
return create;
}
public void setCreate(String create) {
this.create = create;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Set getItemList() {
return itemList;
}
public void setItemList(Set itemList) {
this.itemList = itemList;
}
}
My child model
package com.model;
public class Item{
private Long itemid;
private String itemName;
private String weight;
private cargo cargo;
public Long getItemid() {
return itemid;
}
public void setItemid(Long itemid) {
this.itemid = itemid;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public cargo getCargo() {
return cargo;
}
public void setCargo(cargo cargo) {
this.cargo = cargo;
}
}
And my form
package com.form;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import com.model.Item;
public class cargoForm extends ActionForm {
private Long id;
private String cname;
private String cdate;
private String csource;
private String cdestination;
private String create;
private String status;
private Long[] itemid;
private String[] itemName;
private String[] weight;
private Set itemset = new HashSet();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCdate() {
return cdate;
}
public void setCdate(String cdate) {
this.cdate = cdate;
}
public String getCsource() {
return csource;
}
public void setCsource(String csource) {
this.csource = csource;
}
public String getCdestination() {
return cdestination;
}
public void setCdestination(String cdestination) {
this.cdestination = cdestination;
}
public String getCreate() {
return create;
}
public void setCreate(String create) {
this.create = create;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Long[] getItemid() {
return itemid;
}
public void setItemid(Long[] itemid) {
this.itemid = itemid;
}
public String[] getItemName() {
return itemName;
}
public void setItemName(String[] itemName) {
this.itemName = itemName;
}
public String[] getWeight() {
return weight;
}
public void setWeight(String[] weight) {
this.weight = weight;
}
/*
* public Set getItemset() { return itemset; }
*
* public void setItemset(Set itemset) { this.itemset = itemset; }
*/
public Set getItemDtl() {
if (itemid != null) {
itemset = new HashSet();
System.out.println("cargadd form" + itemid);
for (int i = 0; i < itemid.length; i++) {
Item it = new Item();
// it.setItemId(itemId[i]);
it.setItemName(itemName[i]);
System.out.println("cargadd form" + itemName[i]);
it.setWeight(weight[i]);
itemset.add(it);
System.out.println("cargadd form" + itemset.size());
}
}
return itemset;
}
public void setItemDtl(Set itemset) {
System.out.println("cargadd form" + itemset.size());
this.itemset = itemset;
System.out.println("cargadd form" + itemset.size());
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
cname = "";
csource = "";
cdestination = "";
cdate = "";
status = "";
create = "";
}
}
The error:
Hibernate: select max(itemid) from item
Hibernate: insert into item (itemname, weight, position, id, itemid) values (?, ?, ?, ?, ?)
Hibernate: update cargo set name=?, date=?, source=?, destination=?, createby=?, status=? where id=?
Oct 4, 2010 10:44:08 AM org.hibernate.jdbc.BatchingBatcher doExecuteBatch
SEVERE: Exception executing batch:
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:140)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.action.CargoAction.save(CargoAction.java:125)
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.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Unknown Source)
Oct 4, 2010 10:44:08 AM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
SEVERE: Could not synchronize database state with session
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:140)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.action.CargoAction.save(CargoAction.java:125)
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.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Unknown Source)
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:140)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.action.CargoAction.save(CargoAction.java:125)
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.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Unknown Source)
In the Hibernate mapping file for the id property, if you use any generator class, for that property you should not set the value explicitly by using a setter method.
If you set the value of the Id property explicitly, it will lead the error above. Check this to avoid this error.
its happen when you try to delete the same object and then again update the same object
use this after delete
session.clear();
what i have experienced is that this exception raise when updating object have an id which not exist in table. if you read exception message it says "Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1" which means it was unable to found record with your given id.
To avoid this i always read record with same id if i found record back then i call update otherwise throw "exception record not found".
It looks like, cargo can have one or more item. Each item would have a reference to its corresponding cargo.
From the log, item object is inserted first and then an attempt is made to update the cargo object (which does not exist).
I guess what you actually want is cargo object to be created first and then the item object to be created with the id of the cargo object as the reference - so, essentally re-look at the save() method in the Action class.
It looks like, when you try to delete the same object and then again update the same object, then it gives you this error. As after every update hibernate for safe checking fires how many rows were updated, but during the code the data must have been deleted. Over here hibernate distinguish between the objects based on the key what u have assigned or the equals method.
so, just go through once through your code for this check, or try with implementing equals & hashcode method correctly which might help.
/*
* Thrown when a version number or timestamp check failed, indicating that the
* Session contained stale data (when using long transactions with versioning).
* Also occurs if we try delete or update a row that does not exist.
*
*/
if ( expectedRowCount > rowCount ) {
throw new StaleStateException(
"Batch update returned unexpected row count from update [" + batchPosition +"]; actual row count: " + rowCount +"; expected: " + expectedRowCount);
}
<property name="show_sql">true</property>
This should show you the SQL that is executed and causes the problem.
*The StaleStateException would be thrown only after we successfully deleted one object, and then tried to delete another. The reason for this is, while persisting the objects across sessions, objects must first be deleted from the Session before deleted. Otherwise, subsequent deletes will cause the StaleStateException to be thrown.
Session.Remove(obj);
objectDAO.Delete(obj);
*The problem was that a table must have only one field that is primary key (I had a composite key and this is not a good idea, except for the many to many relation). I have solved using a new id table field auto incremental.
*It can be fix by using Hibernate session.update() -- you need to have the table/view's primary key equal your corresponding bean property (eg. id).
*
For update() and saveOrUpdate() methods, id generator value should be there in the database. For the save() method, id generator is not required.
As mentioned above, be sure that you don't set any id fields which are supposed to be auto-generated.
To cause this problem during testing, make sure that the db 'sees' aka flush this SQL, otherwise everything may seem fine when really its not.
I encountered this problem when inserting my parent with a child into the db:
Insert parent (with manual ID)
Insert child (with autogenerated ID)
Update foreign key in Child table to parent.
The 3. statement failed. Indeed the entry with the autogenerated ID (by Hibernate) was not in the table as a trigger changed the ID upon each insertion, thus letting the update fail with no matching row found.
Since the table can be updated without any Hibernate I added a check whether the ID is null and only fill it in then to the trigger.
This often happens when SQL statements are implemented in some performance costly way (implicit type conversions etc.).
I advice to debug the resulting SQL statements.
To debug turn on SQL logging
Turn on hibernate SQL logging by adding the following lines to your log4j properties file:
# logs the SQL statements
log4j.logger.org.hibernate.SQL=debug
# Logs the JDBC parameters passed to a query
log4j.logger.org.hibernate.type=trace
Before failing you will see the last SQL statement attempted in your log, copy and paste this SQL into an external SQL client and run it.
I had the same as well.Making the Id (0) doing "(your Model value).setId(0)" solved my problem.
please do not set id of child class which is generator class is foreign only set parent class id if your parent class id is assigned...
just do one thing dont set id of child class via setter method your problem will be fix.....definately.
So For my case I noticed hibernate is trying to update the record rather than inserting it and that thrown the exception mentioned.
I finally came to find that my entity had an updatedAt timestamp column:
<timestamp name="updatedDate" column="updated_date" />
and when I was trying to initialize the object i found that the code was
setting this field explicitly.
after removing that setUpdateDate(new Date()) it worked and did an insert instead.
FYI, another way this exception can occur is if:
Your transaction isolation is READ_COMMITTED
Transaction #1 queries for an entity, then deletes that entity
A simultaneous transaction #2 does the same thing
Then this can happen: TX #1 successfully commits before TX #2, then when TX #2 tries to delete the entity (again) it's not there any more - even though it was found by a query earlier in that same transaction. Note this anomaly is allowed with READ_COMMITTED isolation.
In my case the resulting exception looked like this:
HHH000315: Exception executing batch [org.hibernate.StaleStateException:
Batch update returned unexpected row count from update [0]; actual row
count: 0; expected: 1; statement executed: delete from Foobar where id=?],
SQL: delete from Foobar where id=?
if The given id is not exist in the DB ,then you may get this exception.
Exception in thread "main" org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

Categories