Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7428641
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T08:50:05+00:00 2026-05-29T08:50:05+00:00

Currently I have the following Mapping in my Controller: @RequestMapping( value = /add.html, method

  • 0

Currently I have the following Mapping in my Controller:

  @RequestMapping( value = "/add.html", method = RequestMethod.GET )
  public String showAddForm( Map<String, Object> map )
  {
    map.put( "person", new Person() );
    return "form";
  }

  @RequestMapping( value = "/add.html", method = RequestMethod.POST )
  public String processAddForm( @ModelAttribute( "person" ) @Valid Person person, BindingResult result, Map<String, Object> map )
  {
    if ( service.findByName( person.getName() ) != null )
    {
      result.addError( new FieldError( "person", "name", "Person already exists" ) );
    }

    if ( result.hasErrors() )
    {
      return "form";
    }

    service.save( person );
    return "redirect:/index.html";
  }

  @RequestMapping( value = "/{id}/edit.html", method = RequestMethod.GET )
  public String showEditForm( @PathVariable( "id" ) int id, Map<String, Object> map )
  {
    map.put( "person", service.load( id ) );
    return "form";
  }

  @RequestMapping( value = "/{id}/edit.html", method = RequestMethod.POST )
  public String processEditForm( @PathVariable( "id" ) int id, @ModelAttribute( "person" ) @Valid Person person, BindingResult result )
  {
    Person p;
    if ( ( p = service.findByName( person.getName() ) ) != null && person.getId() != id )
    {
      result.addError( new FieldError( "person", "name", "Person already exists" ) );
    }

    if ( result.hasErrors() )
    {
      return "form";
    }

    person.setId( id );
    service.save( person );
    return "redirect:/index.html";
  }

How is it possible to reduce the redundant code?
Maybe by setting the forms action to /save.html and combine processAddForm and processEditForm to

@RequestMapping( value = "/save.html", method = RequestMethod.POST )

But how the code should look like, then?
I just tried it and got some exceptions, because there was already an instance of Person# in Session…

EDIT
Here I given it a try…

Controller method:

  @RequestMapping( value = "/save.html", method = RequestMethod.POST )
  public String onSubmit( @ModelAttribute( "person" ) @Valid Person person, BindingResult result, Map<String, Object> map )
  {
    Person p;
    if ( ( p = service.findByName( person.getName() ) ) != null )
    {
      if ( person.getId() != p.getId() )
      {
        result.addError( new FieldError( "person", "name", "Person already exists" ) );
      }
    }

    if ( result.hasErrors() )
    {
      return "form";
    }

    service.save( person );
    return "redirect:/index.html";
  }

Form:

<c:url value="/save.html" var="formAction" />
<form:form modelAttribute="person" action="${formAction}" method="post">
  <form:errors path="*" cssClass="error" element="div" />
  <form:hidden path="id" />
  <form:label path="name">Name:</form:label>
  <form:input path="name" />
  <input type="submit" value="Submit" />
</form:form>

Adding works, but Editing gives the following Exception:

org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.example.entities.Person#7]
    org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:637)
    org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:305)
    org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:246)
    org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:112)
    org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:677)
    org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:669)
    org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:665)
    com.example.dao.PersonDaoImpl.save(PersonDaoImpl.java:30)
    com.example.dao.PersonDaoImpl.save(PersonDaoImpl.java:1)
    com.example.services.PersonServiceImpl.save(PersonServiceImpl.java:29)
    com.example.services.PersonServiceImpl.save(PersonServiceImpl.java:1)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:616)
    org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
    org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    $Proxy44.save(Unknown Source)
    com.example.controller.PersonController.onSubmit(PersonController.java:65)
    com.example.controller.PersonController$$FastClassByCGLIB$$9c2dc698.invoke(<generated>)
    net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:61)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
    com.example.controller.PersonController$$EnhancerByCGLIB$$a0aff0d2.onSubmit(<generated>)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:616)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:311)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:101)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:201)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)

EDIT2:
PersonServiceImpl:

  @Override
  @Transactional
  public void save( Person person )
  {
    dao.save( person );
  }

PersonDaoImpl:

  @Override
  public void save( Person person )
  {
    try
    {
      sessionFactory.getCurrentSession().saveOrUpdate( person );
    }
    catch( NonUniqueObjectException e )
    {
      sessionFactory.getCurrentSession().merge( person );
    }
  }

Is this the correct way? Maybe a better solution?

EDIT3

  @Override
  public void save( Person person )
  {
    if ( load( person.getId() ) != null)
    {
      sessionFactory.getCurrentSession().merge( person );
    }
    else
    {
      sessionFactory.getCurrentSession().save( person );
    }
  }

  @Override
  public Person load( int id )
  {
    return ( Person ) sessionFactory.getCurrentSession().load( Person.class, id );
  }

Is this a better solution?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T08:50:06+00:00Added an answer on May 29, 2026 at 8:50 am

    It looks like you’re trying to save an object with the same id, and that object is not attached to the hibernate session.

    You probably edited Person‘s name and tried to save it. The person with that name is not found, but the person with the same id exists in database, hence error.

    Either use merge() or, in your service, fetch the person first (to make it connected to hibernate’s session), update necessary fields and save it to DB.

    To explain better:

    @RequestMapping( value = "/save.html", method = RequestMethod.POST )
      public String onSubmit( @ModelAttribute( "person" ) @Valid Person person, BindingResult result, Map<String, Object> map )
      {
        Person p;
      // You changed the name so it doesn't find anything here and proceeds without errors
        if ( ( p = service.findByName( person.getName() ) ) != null ) 
        {
          if ( person.getId() != p.getId() )
          {
            result.addError( new FieldError( "person", "name", "Person already exists" ) );
          }
        }
    
        if ( result.hasErrors() )
        {
          return "form";
        }
    
    //the code breaks here, person is not attached to hibernate session and you're trying to save it. Modify your service code to use merge() or to fetch the person from database before saving it.
        service.save( person );  
        return "redirect:/index.html";
      }
    

    edit

    If you use merge() then you don’t have to test anything. Hibernate is clever enough to know if you’re saving new instance or saving changes to an already persisted one. The other way would be to test, in your controller, if person.id is set, and call an apropriate method in your service (service.save or service.update). It really depends on how much do you want to depend on hibernate’s cleverness.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following 2 methods... @GET @Path(/{solution}) public Response test(@PathParam(solution) String solution, @Context
I currently have the following MySQL statement to replace the HTML entity for a
currently I have the following code: String select = qry.substring(select .length(),qry2.indexOf( from )); String[]
I currently have the following named query that wraps around a stored procedure:- <hibernate-mapping>
I currently have the following CSS for my 4 columns which might grow to
I currently have the following row in my table: course_data: user_id days <-- This
I currently have the following objects persisting successfully: Person first name, etc. Exams title,
I currently have the following js code function clearMulti(option) { var i; var select
I currently have code that does the following: private final static ExecutorService pool =
I currently have a class file with the following enumeration: using System; namespace Helper

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.