Results 1 to 5 of 5

Thread: handle JPA exceptions in Spring

Hybrid View

  1. #1
    Join Date
    Mar 2010
    Posts
    12

    Default handle JPA exceptions in Spring

    Hi,
    I have a question according proper exception handling when using Spring and JPA.

    So I have a method for looking for user:
    Code:
    @Transactional(readOnly = true)
       public User findUserByName(String name){
           return getUserDAO().findByName(name);
       }
    DAO class:
    Code:
    public User findByName(String name) {
            Query query = getEntityManager().createQuery("FROM User user WHERE user.username = :username");
            query.setParameter("username", name);
            return (User) query.getSingleResult();
        }
    NoResultFound exception is thrown when username is not found which is translated into org.springframework.dao.EmptyResultDataAccessExcep tion, just like here:
    HTML Code:
    Caused by: org.springframework.dao.EmptyResultDataAccessException: No entity found for query
        at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:295)
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:350)
    EmptyResultDataAccessException is unchecked, and in my service class I write:
    Code:
    @Transactional(readOnly = true)
       public User findUserByName(String name){
           User foundedUser = null;
           try {
               foundedUser = getUserDAO().findByName(name);
           } catch (org.springframework.dao.EmptyResultDataAccessException ex) {
               System.out.println("No Object found");
           }
           return foundedUser;
       }
    I think that it is a little strange for JPA to throw an exception when something is not found, it's not a good behavior; as far as I know using Hibernate - will not give any exception, and will return null.

    Is such handling of exception is correct or not? Should I handle exceptions for other services methods (findyById, update) in the same way?

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    It depends, here you are stating that you are expecting 1 row, no more no less. Hence JPA throws an exception (as specified) if there are no rows returned. This exception is converted by spring to an EmptyResultDataAccessException.

    If instead of getSingleResult you would use getResultList (0 or more results) no exception is raised because well 0 rows is valid.

    Hibernate would do the same if you create a query and expect a singleresult (i.e. uniqueresult in hibernate) then you would also get an exception. The only exception to this rule is when you use find (or get in hibernate) with an id, if it doesn't exist you will get null instead of an exception.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3
    Join Date
    Mar 2010
    Posts
    10

    Default

    Hi Marten,
    Thanks for your nice replay. I have one question to you. For simple database read operation, should i use transaction if i want to reduce database round trip? Two way i can close session, one is after finish each transaction using aop and another one is directly close session. If i want to reduce database round trip which one is the best?

  4. #4
    Join Date
    Mar 2010
    Posts
    12

    Default

    Thanks for reply. But still to my mind it's not very good to catch runtime exceptions. But as far as I see there is no better way of doing the exception handling.

    unam, could you please use your own thread for questions? You are asking things which are not related to that thread. What do you mean by database round trip? For read operation I'm using annotation Transaction(readOnly=true), it actually opens transaction only for reading while trying to insert something in the method will raise an exception. Read that for more information on transactions http://forum.springsource.org/showthread.php?t=61086

  5. #5
    Join Date
    Mar 2010
    Posts
    10

    Default

    Hi ALincoln,
    For read operation, should i use transaction arrtibute support or without any transaction arrtibute? Anyway i got my ans after read the following tutorial-

    http://www.ibm.com/developerworks/ja....html#strategy

Posting Permissions

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