gpt4 book ai didi

hibernate - 在Spring MVC中,在何处捕获数据库异常

转载 作者:行者123 更新时间:2023-12-04 08:52:34 25 4
gpt4 key购买 nike

我正在上面(http://viralpatel.net/blogs/spring3-mvc-hibernate-maven-tutorial-eclipse-example/)建议的结构中使用。我尝试添加重复的条目,这导致以下异常:

SEVERE: Servlet.service() for servlet [appServlet] in context with path [/cct] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: Duplicate entry 'a@b.com' for key 'PRIMARY'; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Duplicate entry 'a@b.com' for key 'PRIMARY'] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'a@b.com' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at << removed for readability>> org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy26.addUser(Unknown Source)
at com.bilitutor.cct.control.HomeController.signup(HomeController.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
<< removed for readability>>

我有以下问题:
  • 为什么异常是由 Controller (userService.addUser(user)中的com.bilitutor.cct.control.HomeController)而不是DAO(sessionFactory.getCurrentSession().save(user);)捕获,然后冒泡到 Controller ?
  • 我知道我收到了org.springframework.dao.DataIntegrityViolationException,因为我使用的是@Repository批注,它可能会进行异常转换(如果我错了,请更正我)。在那种情况下,当我捕获到异常时,如何找到该异常的错误代码?
  • 作为最佳实践,捕获异常的最佳位置是哪一层(DAO,服务或 Controller )?

  • 相关类(class):

    Controller :
    package com.bilitutor.cct.control;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.dao.DataIntegrityViolationException;
    import org.springframework.web.bind.annotation.ModelAttribute;

    import com.bilitutor.cct.bean.*;
    import com.bilitutor.cct.service.*;

    /**
    * Handles requests for the application home page.
    */
    @Controller
    public class HomeController {

    @Autowired
    UserService userService;

    @ModelAttribute("user")
    public User getUserObect() {
    return new User();
    }

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    /**
    * Landing page. Just return the login.jsp
    */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Model model) {
    logger.info("home() called");
    return "login";
    }

    /**
    * Login. Either forward to the user's homepage or return back the error
    */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model) {
    logger.info("login() called");
    return "login";
    }

    /**
    * New User signup. If user already exists, send back the error, or send an email and forward to the email validation page
    */
    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public String signup(@ModelAttribute("user")User user, BindingResult result) {
    logger.info("signup() : email="+user.getEmail()+" pass="+user.getPassword()+" accessCode="+user.getAccessCode());
    userService.addUser(user);
    return "login";
    }

    }

    服务:
    package com.bilitutor.cct.service;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import com.bilitutor.cct.dao.UserDAO;
    import com.bilitutor.cct.bean.User;

    @Service
    public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;

    @Transactional
    public void addUser(User user) {
    userDAO.addUser(user);
    }

    @Transactional
    public void removeUser(String email) {
    userDAO.removeUser(email);
    }

    }

    道:
    package com.bilitutor.cct.dao;

    import com.bilitutor.cct.bean.User;

    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;

    @Repository
    public class UserDAOImpl implements UserDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
    }

    public void addUser(User user) {
    sessionFactory.getCurrentSession().save(user);
    }

    public void removeUser(String email) {
    User user = (User) sessionFactory.getCurrentSession().load(User.class, email);
    if (user!=null) {
    sessionFactory.getCurrentSession().delete(user);
    }

    }
    }

    最佳答案

    服务层发生异常。你可以看到它的踪影
    at com.sun.proxy.$Proxy26.addUser(Unknown Source)

    @Transactional
    public void addUser(User user) {
    userDAO.addUser(user);
    }

    如先前的回答所述,您的事务边界位于服务层,因此在那里发生异常。

    我建议从服务方法中捕获/抛出适当的业务异常(已检查的异常)。服务方法结合了您的业务逻辑,因此,如果发生任何错误,应通过服务方法引发的异常将其正确地传达给外部世界。例如:WeakPasswordException,UserNameExistsException等

    关于 org.springframework.dao.DataIntegrityViolationException尝试调用 getCause()查看包装的异常

    关于hibernate - 在Spring MVC中,在何处捕获数据库异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18094524/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com