Lou*_*uis 5 java spring hibernate spring-data-jpa
如何解决“无法执行语句;SQL [n/a];嵌套异常是 org.hibernate.exception.SQLGrammarException:无法执行语句”?
我在运行我的应用程序时遇到了这样的错误。我分享我的代码片段相关服务和存储库。当我更改评论和帖子的报告状态时,我会得到成功和失败的对比结果。
配置的yaml文件如下。
jpa:
open-in-view: false
database: MYSQL
generate-ddl: true
show-sql: true
hibernate:
ddl-auto: update
naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
properties:
hibernate:
use-new-id-generator-mappings: false
enable_lazy_load_no_trans: true
format_sql: true
use_sql_comments: true
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
# dialect: org.hibernate.spatial.dialect.mysql.MySQL5SpatialDialect
default_batch_fetch_size: 100
search:
autoregister_listeners: false
indexing_strategy: manual
default:
indexmanager: elasticsearch #5.6.16
elasticsearch:
host: http://localhost:9200
index_schema_management_strategy: update #update
#username: user
#password: password
log:
json_pretty_printing: true
required_index_status: yellow
dynamic_mapping: true
update_all_types: true
Run Code Online (Sandbox Code Playgroud)
// RestAdminReportController //
@JsonView(Views.WebAdminJsonView.class)
@PostMapping(path = "/{id}/changeStatus")
public ResponseEntity<Map<String, Object>> changeStatus(@PathVariable long id, @RequestParam ReportStatus reportStatus, @RequestParam long reportId) {
Map<String, Object> map = new HashMap<>();
User loginUser = authUtils.getCurrentUser();
log.info("ReportID : {}, PostingID : {}, ChangeStatus : {}", reportId, id, reportStatus);
ReportPosting report = adminReportPostingService.findById(reportId);
adminReportPostingService.updateAll(report.getRelation().getPosting(), reportStatus);
boolean isBlind = reportStatus.equals(ReportStatus.BLOCK);
postingService.blindPosting(id, loginUser, isBlind);
map.put("resultCode", "1000");
map.put("data", "");
return new ResponseEntity<>(map, HttpStatus.OK);
}
@JsonView(Views.WebAdminJsonView.class)
@PostMapping(path = "/{id}/changeCommentStatus")
public ResponseEntity<Map<String, Object>> changeCommentStatus(@PathVariable long id, @RequestParam ReportStatus reportStatus, @RequestParam long reportId) {
Map<String, Object> map = new HashMap<>();
User loginUser = authUtils.getCurrentUser();
log.info("ReportID : {}, CommentID : {}, ChangeStatus : {}", reportId, id, reportStatus);
ReportComment report = adminReportCommentService.findById(reportId);
adminReportCommentService.updateAll(report.getRelation().getComment(), reportStatus);
boolean isBlind = reportStatus.equals(ReportStatus.BLOCK);
postingService.blindComment(id, loginUser, isBlind);
map.put("resultCode", "1000");
map.put("data", "");
return new ResponseEntity<>(map, HttpStatus.OK);
}
// ReportCommentRepository //
public interface ReportCommentRepository extends JpaRepository<ReportComment, Long> {
...
@Modifying
@Query("update ReportComment rc set rc.reportStatus = :status where rc.relation.comment.id = :#{#comment.id}")
int updateAll(@Param("comment")Comment comment, @Param("status") ReportStatus status);
}
// ReportPostingRepository //
public interface ReportPostingRepository extends JpaRepository<ReportPosting, Long> {
...
@Modifying
@Query("update ReportPosting rc set rc.reportStatus = :status where rc.relation.posting.id = :#{#posting.id}")
int updateAll(@Param("posting") Posting posting, @Param("status") ReportStatus status);
}
// Posting Model //
@Data
@EqualsAndHashCode(callSuper = false)
@Entity
@DiscriminatorColumn(columnDefinition = "char(2)", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("PO")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@NoArgsConstructor
@AllArgsConstructor
@ToString()
@Where(clause = "is_delete = false")
@DynamicUpdate
@AnalyzerDef(name = "text_analyzer",
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = StandardFilterFactory.class),
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(factory = StopFilterFactory.class),
}
)
@Table(indexes = {@Index(name = "IDX_TYPE", columnList = "dtype")})
public abstract class Posting extends BaseEntity implements INotification, WithCondition, IActivity, IYoutube, IPhotoAlbum {
...
}
// Comment Model //
@Data
//@Indexed(index = ElasticsearchConfig.INDEX_NAME)
@Entity
@DynamicUpdate
@NoArgsConstructor
@AllArgsConstructor
@Builder
@EqualsAndHashCode(callSuper = false, of = {"id"})
@ToString
@Table(indexes = {@javax.persistence.Index(name = "IDX_POSTING", columnList = "posting_id")})
@JsonIgnoreProperties({"hibernateLazwyInitializer"})
@AnalyzerDef(name = "comment",
tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
@TokenFilterDef(factory = StandardFilterFactory.class),
@TokenFilterDef(factory = LowerCaseFilterFactory.class),
@TokenFilterDef(factory = StopFilterFactory.class),
}
)
@AnalyzerDef(name = "comment_remove_nickname_analyzer", charFilters =
{
@CharFilterDef(factory = PatternReplaceCharFilterFactory.class, params =
{
@Parameter(name = "pattern", value = "(\\[.*\\])"),
@Parameter(name = "replacement", value = "")
})
}, tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class), filters =
{
@TokenFilterDef(factory = StandardFilterFactory.class), @TokenFilterDef(factory = LowerCaseFilterFactory.class),
})
public class Comment extends BaseEntity implements INotification, IActivity {
...
}
Run Code Online (Sandbox Code Playgroud)
运行以下函数后,我成功更新了评论项。
adminReportCommentService.updateAll(report.getRelation().getComment(), reportStatus);
Run Code Online (Sandbox Code Playgroud)
相反,还有另一个函数,但逻辑相似。运行此函数后,出现如下失败。
adminReportPostingService.updateAll(report.getRelation().getPosting(), reportStatus);
Run Code Online (Sandbox Code Playgroud)
[Admin][2022-08-10 00:55:22][TRACE][BasicBinder.java][bind(64)] : binding parameter [1] as [INTEGER] - [2]
[Admin][2022-08-10 00:55:22][TRACE][BasicBinder.java][bind(64)] : binding parameter [2] as [BIGINT] - [2003441]
[Admin][2022-08-10 00:55:22][WARN ][SqlExceptionHelper.java][logExceptions(137)] : SQL Error: 1064, SQLState: 42000
[Admin][2022-08-10 00:55:22][ERROR][SqlExceptionHelper.java][logExceptions(142)] : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set report_status=2 where id=2003441' at line 1
[Admin][2022-08-10 00:55:22][INFO ][ProxyLeakTask.java][cancel(91)] : Previously reported leaked connection com.mysql.cj.jdbc.ConnectionImpl@20d18bbc on thread http-nio-8081-exec-6 was returned to the pool (unleaked)
[Admin][2022-08-10 00:55:22][ERROR][CommonExceptionHandler.java][paramViolationError(99)] : paramViolationError
org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:259)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:145)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
at jdk.proxy2/jdk.proxy2.$Proxy233.updateAll(Unknown Source)
at net.infobank.moyamo.service.AdminReportPostingService.updateAll(AdminReportPostingService.java:44)
at net.infobank.moyamo.service.AdminReportPostingService$$FastClassBySpringCGLIB$$636acc8e.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:779)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692)
at net.infobank.moyamo.service.AdminReportPostingService$$EnhancerBySpringCGLIB$$d8cddc1f.updateAll(<generated>)
at net.infobank.moyamo.controller.RestAdminReportController.changeStatus(RestAdminReportController.java:85)
at net.infobank.moyamo.controller.RestAdminReportController$$FastClassBySpringCGLIB$$b2100f08.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:779)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:89)
at net.infobank.moyamo.aop.AdminRestAspect.restApiControllerAdviceAround(AdminRestAspect.java:36)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:634)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:624)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:72)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692)
at net.infobank.moyamo.controller.RestAdminReportController$$EnhancerBySpringCGLIB$$593eb73f.changeStatus(<generated>)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:517)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:584)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:218)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:218)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter.doFilterInternal(OAuth2AuthorizationRequestRedirectFilter.java:178)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
at org.springframewor
我添加了 updateReportStatus 函数,因为“updateAll”函数更改仅更新报告状态。
@Transactional
public int updateAll(Posting posting, ReportStatus status) {
return reportPostingRepository.updateAll(posting, status);
}
@Transactional
public int updateReportStatus(ReportPosting report, ReportStatus status) {
return reportPostingRepository.updateReportStatus(report, status);
}
Run Code Online (Sandbox Code Playgroud)
@Modifying
@Query("update ReportPosting rp set rp.reportStatus = :status where rp.id = :#{#report.id}")
int updateReportStatus(@Param("report") ReportPosting report, @Param("status") ReportStatus status);
Run Code Online (Sandbox Code Playgroud)
ReportPosting report = adminReportPostingService.findById(reportId);
// adminReportPostingService.updateAll(report.getRelation().getPosting(), reportStatus); // By this line, getting error.
adminReportPostingService.updateReportStatus(report, reportStatus);
Run Code Online (Sandbox Code Playgroud)
最后,我可以通过reportStatus 更新reportPosting 项目。
| 归档时间: |
|
| 查看次数: |
17808 次 |
| 最近记录: |