gpt4 book ai didi

java - Service层异常处理

转载 作者:搜寻专家 更新时间:2023-11-01 03:36:44 25 4
gpt4 key购买 nike

请问如何解决下面描述的问题:

有一个应用程序(涉及使用 Hibernate 和 Spring 框架)具有 3 层:DAO、服务和 Controller 。我想避免在数据库中保存重复的实体。我通过在 DB 级别和 bean 中的注释中使用约束来实现它 (@Table(name = "artist", uniqueConstraints = {@UniqueConstraint(columnNames = "artist_name")}))。逻辑假设如果我尝试添加重复的实体,则会抛出异常。我尝试在服务层处理异常,但未能成功。我的意思是,即使我明确注意到抛出的所有异常,应用程序也因为异常而无法继续工作。为了更清楚,我引用了下面的代码:

DAO 层

@Override
public void saveEntity(Client client) {
Session session = sessionFactory.getCurrentSession();
session.save(client);
}

服务层

@Transactional
@Override
public boolean saveEntity(Artist entity) {
boolean completedState = false;
try {
//method from DAO-layer
artistDAO.saveEntity(entity);
} catch (ConstraintViolationException | UnexpectedRollbackException e) {
return completedState;
}
return completedState = true;
}

Controller

@RequestMapping(value="addArtist", method=RequestMethod.POST)
public String processNewArtistForm(@ModelAttribute Artist artist, Model model) {
//If duplicated artistName prompts to be saved an saveEntity(entity) returns "false". Entity is failed to save.
boolean completedState = false;
completedState = artistService.saveEntity(artist);
if (completedState == true) {
List<Artist> listOfArtists = artistService.getListOfEntities();
model.addAttribute("listOfArtists", listOfArtists);
} else {
model.addAttribute("errorMessage", "An artist under present name already exists");
return "newArtist";
}
return "listOfArtists";
}

当我尝试保存重复的实体时 Tomcat 的通知

Type Exception report

message Request processing failed; nested exception is org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:720)
org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:521)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy29.saveEntity(Unknown Source)
web.ArtistsListController.processNewArtistForm(ArtistsListController.java:66)
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:606)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.9 logs.

请问这些架构解决方案是否正确?提前谢谢你。

最佳答案

为什么不在保存前检查重复项?:

@Transactional
@Override
public void saveEntity(Client client) {
Session session = sessionFactory.getCurrentSession();
// session.get() will always query the database and will return null
// if no rows found
if (session.get(Client.class,client.getId()==null) {
session.save(client);
//flush session cache
session.flush();
}
}

关于java - Service层异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29393983/

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