Results 1 to 5 of 5

Thread: UniqueKeyConstraint Violation handling

  1. #1

    Default UniqueKeyConstraint Violation handling

    In one of my entity, there is just one Unique, Not Null column.

    Code:
        @Column(unique=true)
        private String job_role = "DUMMY";
        
    }
    But, when user tries to insert same role twice, he is shown a STACK TRACE with message and Internal error has occured. What I had wanted to be shown is actually shown in LOG file instead of screen as below -

    Code:
    2012-03-15 22:21:49,672 [http-8080-2] ERROR org.hibernate.util.JDBCExceptionReporter - Duplicate entry 'DUMMY' for key 'job_role'
    I tried overriding persist method inside Entity class and wrap it in TRY-CATCH block but still the stack trace is shown.
    Please suggest how to show better message in case of this Exception.

    Thanks

  2. #2
    Join Date
    Jun 2010
    Posts
    440

    Default

    @fortm,

    There are more than one way for implementing it...

    1. Before inserting the value, run a select statement for verifying uniqueness.
    2. You can use JPA prepersist anotation for executing referred select statement.


    I hope it helps you.

    Roogards
    jD
    Last edited by delgad9; Mar 15th, 2012 at 02:58 PM. Reason: clean up

  3. #3

    Default

    thanks i have been able to do this by this code change -

    1) I created a finder in entity - Mst_job_role.findMst_job_rolesByJob_roleEquals
    2) Override create method in entity's controller and changed it as below -
    Code:
      @RequestMapping(method = RequestMethod.POST)
    	public String create(@Valid Mst_job_role mst_job_role,
    			BindingResult bindingResult, Model uiModel,
    			HttpServletRequest httpServletRequest) {
    		if (bindingResult.hasErrors()) {
    			uiModel.addAttribute("mst_job_role", mst_job_role);
    			return "mst_job_roles/create";
    		}
    		//uiModel.asMap().clear();
    		if (Mst_job_role.findMst_job_rolesByJob_roleEquals(mst_job_role.getJob_role()).getResultList().size() == 0) {
    			mst_job_role.persist();
    			return "redirect:/mst_job_roles/"+ encodeUrlPathSegment(mst_job_role.getId().toString(),httpServletRequest);
    		} else
    			return "mst_job_roles/create";
    	}
    I had to comment clearing of uiModel
    Code:
    //uiModel.asMap().clear();
    as I am sending back to create page if job role already exists.

  4. #4
    Join Date
    Jun 2010
    Posts
    440

    Default

    @fortm,

    Very elegant indeed!...

    Congrats & B. Roogards
    jD

  5. #5

    Default

    thanks @delgad9
    What I am trying to do next is also show a message in browser that "This Job Role already exists" using @ResponseBody as in this post
    http://www.raistudies.com/spring/spr...ations-jquery/

    I don't know if there is a simpler way..

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •