【问题标题】:Spring data jdbc error BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar, while trying to save simple AggregateSpring数据jdbc错误BadSqlGrammarException: PreparedStatementCallback;糟糕的 SQL 语法,同时尝试保存简单的聚合
【发布时间】:2020-09-10 23:02:08
【问题描述】:

当我尝试将完整的聚合(只有两个实体)spring-data 保存在错误下方时,我的域模型对象低于 DDL 和 spring 版本。

所以我认为要么我没有正确定义我的聚合或我的 DDL,要么在 spring-data-jdbc 中遇到了一个阻止程序。

我在这里创建了示例 git repo: https://github.com/rajeshhazari/spring-boot-samples

对此的任何帮助和建议将不胜感激。

我的实体、Repo 和 Junit 测试用例和堆栈跟踪:

org.springframework.data.relational.core.conversion.DbActionExecutionException: Failed to execute DbAction.Delete(rootId=1, propertyPath=appUsersAuthList)

    at org.springframework.data.jdbc.core.AggregateChangeExecutor.execute(AggregateChangeExecutor.java:89)
    at org.springframework.data.jdbc.core.AggregateChangeExecutor.lambda$execute$0(AggregateChangeExecutor.java:50)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.springframework.data.relational.core.conversion.DefaultAggregateChange.forEachAction(DefaultAggregateChange.java:116)
    at org.springframework.data.jdbc.core.AggregateChangeExecutor.execute(AggregateChangeExecutor.java:50)
    at org.springframework.data.jdbc.core.JdbcAggregateTemplate.store(JdbcAggregateTemplate.java:339)
    at org.springframework.data.jdbc.core.JdbcAggregateTemplate.save(JdbcAggregateTemplate.java:149)
    at org.springframework.data.jdbc.repository.support.SimpleJdbcRepository.save(SimpleJdbcRepository.java:55)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.data.repository.core.support.ImplementationInvocationMetadata.invoke(ImplementationInvocationMetadata.java:72)
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:382)
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:205)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:549)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:155)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy69.save(Unknown Source)
    at com.example.test.springjdbcsample1.springjdbcsampletest1Tests.repositoryTest(springjdbcsampletest1Tests.java:54)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [DELETE FROM "appusers_auth" WHERE "appusers_auth"."userid" = ?]; nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "appusers_auth" not found; SQL statement:
DELETE FROM "appusers_auth" WHERE "appusers_auth"."userid" = ? [42102-200]
    at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:235)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
    at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1443)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:862)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:883)
    at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(NamedParameterJdbcTemplate.java:321)
    at org.springframework.data.jdbc.core.convert.DefaultDataAccessStrategy.delete(DefaultDataAccessStrategy.java:222)
    at org.springframework.data.jdbc.core.JdbcAggregateChangeExecutionContext.executeDelete(JdbcAggregateChangeExecutionContext.java:144)
    at org.springframework.data.jdbc.core.AggregateChangeExecutor.execute(AggregateChangeExecutor.java:74)
    ... 92 more
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "appusers_auth" not found; SQL statement:
DELETE FROM "appusers_auth" WHERE "appusers_auth"."userid" = ? [42102-200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:453)
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
    at org.h2.message.DbException.get(DbException.java:205)
    at org.h2.message.DbException.get(DbException.java:181)
    at org.h2.command.Parser.readTableOrView(Parser.java:7628)
    at org.h2.command.Parser.readTableOrView(Parser.java:7599)
    at org.h2.command.Parser.readSimpleTableFilter(Parser.java:1350)
    at org.h2.command.Parser.parseDelete(Parser.java:1377)
    at org.h2.command.Parser.parsePrepared(Parser.java:914)
    at org.h2.command.Parser.parse(Parser.java:843)
    at org.h2.command.Parser.parse(Parser.java:815)
    at org.h2.command.Parser.prepareCommand(Parser.java:738)
    at org.h2.engine.Session.prepareLocal(Session.java:657)
    at org.h2.engine.Session.prepareCommand(Session.java:595)
    at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1235)
    at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:76)
    at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:352)
    at com.zaxxer.hikari.pool.ProxyConnection.prepareStatement(ProxyConnection.java:337)
    at com.zaxxer.hikari.pool.HikariProxyConnection.prepareStatement(HikariProxyConnection.java)
    at org.springframework.jdbc.core.PreparedStatementCreatorFactory$PreparedStatementCreatorImpl.createPreparedStatement(PreparedStatementCreatorFactory.java:237)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:615)
    ... 98 more

@Table("APPUSERS")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AppUsers implements Serializable {
    private @Id
    Long userid;
    private String username;
    private String password;
    private String email;

    @MappedCollection(idColumn="userid", keyColumn="userid")
    private Set<AppUsersAuth> appUsersAuthList ;
}
public interface AppUserRepository extends CrudRepository<AppUsers, Long> {

    @Query("select * from APPUSERS where upper(email) = upper(:email)   ")
    AppUsers findByEmail(@Param("email") String email);
}
@Table("appusers_auth")
@Data
public  class AppUsersAuth {
    @Column("auth_user_id")
    private Long authUserId;
    @Column("userid")
    private Long userid;
    private String email;
    @Column("role_id")
    private String roleId;
    @Column("username")
    private String username;


}
CREATE TABLE APPUSERS(
  userid identity not null auto_increment PRIMARY KEY ,
  username VARCHAR(100) not null unique ,
  password VARCHAR(100) not null,
  email VARCHAR(100) not null unique
);

CREATE TABLE appusers_auth (
 auth_user_id identity not null auto_increment PRIMARY KEY  ,
 userid BIGINT NOT NULL ,
 username text,
 email text NOT NULL,
 role_id VARCHAR(50) NOT NULL,
 updated_time timestamp default CURRENT_TIMESTAMP
);
@ActiveProfiles("test")
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SpringjdbcsampletestApp.class)
@TestPropertySource(locations="classpath:application-test.properties")
public class springjdbcsampletest1Tests {

    @Autowired
    AppUserRepository appUserRepository;

    @Test
    void repositoryTest() {
        //appUserRepository.deleteAll();
        AuthoritiesMaster authoritiesMaster = new AuthoritiesMaster();
        authoritiesMaster.setRoleId("role_basic");
        authoritiesMaster.setRoledesc("Basic Role Desc");

        //appUsersAuth.setRoleId(authoritiesMaster.getRoleId());
        AppUsersAuth appUsersAuth = new AppUsersAuth();
        appUsersAuth.setEmail("test1@mail.com");
        appUsersAuth.setRoleId("role_basic");

        AppUsers appUsers = new AppUsers();
        appUsers.setUsername("test1");
        appUsers.setEmail("test1@mail.com");
        appUsers.setPassword("test123");


        appUsersAuth.setUsername(appUsers.getUsername());
        appUsersAuth.setUserid(appUsers.getUserid());
        appUsers = appUserRepository.save(appUsers);
        appUsersAuth.setUserid(appUsers.getUserid());
        appUsers = appUserRepository.save(appUsers);
        Assertions.assertThat(appUsers).isNotNull();
        Assertions.assertThat(appUsers.getAppUsersAuthList()).isNotNull();
        Set<AppUsersAuth> appUsersAuthList = appUsers.getAppUsersAuthList();
        for (final AppUsersAuth usersAuth : appUsersAuthList) {

            /*Assertions.assertThat(usersAuth.getAppAuthoritiesMasterList()).isNotNull();
            List<AuthoritiesMaster> authoritiesMasterList = usersAuth.getAppAuthoritiesMasterList();
            authoritiesMasterList.forEach(appUsersAuthMaster -> {
                Assertions.assertThat(appUsersAuthMaster).isNotNull();
                Assertions.assertThat(appUsersAuthMaster.getRoleId()).isEqualToIgnoringCase("role_basic");
            });*/
        }
        Assertions.assertThat(appUsers.getEmail()).isNotNull();
    }

}

【问题讨论】:

    标签: spring-boot solr java-11 spring-data-jdbc


    【解决方案1】:

    堆栈跟踪的根本原因给出了重要提示:

    Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "appusers_auth" not found; SQL statement:
    DELETE FROM "appusers_auth" WHERE "appusers_auth"."userid" = ? [42102-200]
    

    你有创建语句

    CREATE TABLE appusers_auth (
    ...
    

    但这实际上创建了一个全大写名称的表。 而 Spring Data JDBC 使用带引号的标识符并在所有小写名称中查找 appusers_auth

    要解决问题,请使用

    CREATE TABLE "appusers_auth" (
    ...
    

    即在创建脚本中引用表名。 或者(可能更可取)在 @Table 注释中使用全部大写。

    【讨论】:

    • 谢谢,@Jens Schauder,我会在周末尝试您建议的更改并在此处更新。
    • 更新:再次感谢 Jens Schauder,对于这个包含两个实体的聚合模型,我已经按照您的建议更改了代码,并且所有测试都通过了。我还有一个关于聚合的问题,聚合模型与三个实体:对于我有第三个实体与 AuthoritiesMaster 表的情况,我们可以在其中定义角色级别权限,你认为这个主表应该是这个聚合的一部分。跨度>
    • 更新:再次感谢 Jens Schauder,对于这个包含两个实体的聚合模型,我已经按照您的建议更改了代码,并且所有测试都通过了。 Github链接:[github.com/rajeshhazari/spring-boot-samples]我有另一个关于聚合的问题,聚合模型与三个实体:对于我有第三个实体与权限主表的情况,我们可以在其中定义角色级别权限,你认为这个主表应该成为这个集合的一部分。 ` Appusers -> AppusersAuth -> AuthoritiesMaster { private String roleId;私有字符串角色描述; }`。
    • 请不要在 cmets 中提问。让它成为一个适当的问题,这样其他人就有机会找到它并从它和它的答案中获利。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    相关资源
    最近更新 更多