简体   繁体   English

Spring 引导 JPA 初始化数据 - SQL 语句中的语法错误...预期“标识符”

[英]Spring Boot JPA initialize data - Syntax error in SQL statement ... expected "identifier"

Try to implement data into my Spring Boot application at the start up.尝试在启动时将数据实现到我的 Spring 引导应用程序中。 As I researched it should be working like this:正如我所研究的那样,它应该像这样工作:

user_role class:用户角色 class:

@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UserRole {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String role;
}

schema.sql架构.sql

CREATE TABLE `user_role` (
    `id` bigint(20) NOT NULL,
    `role` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 

data.sql数据.sql

INSERT INTO user_role (role) VALUES ('ADMIN');
INSERT INTO user_role (role) VALUES ('USER');

application.properties应用程序属性

spring.jpa.hibernate.ddl-auto=none
spring.jpa.defer-datasource-initialization=true
spring.sql.init.mode=always

But if I try this I only got the following error when I am building the application:但是,如果我尝试这样做,我在构建应用程序时只会收到以下错误:

Syntax error in SQL statement "CREATE TABLE USER_ROLE ( ID BIGINT([*]20) NOT NULL, ROLE VARCHAR(255) DEFAULT NULL, PRIMARY KEY ( ID ) ) ENGINE=INNODB DEFAULT CHARSET=UTF8MB4"; Syntax error in SQL statement "CREATE TABLE USER_ROLE ( ID BIGINT([*]20) NOT NULL, ROLE VARCHAR(255) DEFAULT NULL, PRIMARY KEY ( ID ) ) ENGINE=INNODB DEFAULT CHARSET=UTF8MB4"; expected "ARRAY, INVISIBLE, VISIBLE, NOT, NULL, AS, DEFAULT, GENERATED, ON, NOT, NULL, AUTO_INCREMENT, DEFAULT, NULL_TO_DEFAULT, SEQUENCE, SELECTIVITY, COMMENT, CONSTRAINT, COMMENT, PRIMARY, UNIQUE, NOT, NULL, CHECK, REFERENCES, AUTO_INCREMENT, ., )"; expected "ARRAY, INVISIBLE, VISIBLE, NOT, NULL, AS, DEFAULT, GENERATED, ON, NOT, NULL, AUTO_INCREMENT, DEFAULT, NULL_TO_DEFAULT, SEQUENCE, SELECTIVITY, COMMENT, CONSTRAINT, COMMENT, PRIMARY, UNIQUE, NOT, NULL, CHECK, REFERENCES, AUTO_INCREMENT, ., )"; SQL statement: CREATE TABLE user_role ( id bigint(20) NOT NULL, role varchar(255) DEFAULT NULL, PRIMARY KEY ( id ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 [42001-202] SQL statement: CREATE TABLE user_role ( id bigint(20) NOT NULL, role varchar(255) DEFAULT NULL, PRIMARY KEY ( id ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 [42001-202]

Does someone know what is wrong?有人知道出了什么问题吗?

If you created the user_role table with your script then the problem is the id column definition where the AUTO_INCREMENT is missing from it.如果您使用脚本创建了user_role表,那么问题出在id列定义中,其中缺少AUTO_INCREMENT Because you want to insert fields without manually adding the id values.因为您想在不手动添加 id 值的情况下插入字段。 So the correct sql code for the table creation should be:因此,用于表创建的正确 sql 代码应该是:

CREATE TABLE `user_role` (
    `id` bigint(20) NOT NULL AUTO_INCREMENT,
    `role` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 

In this case the insert sql code will work fine.在这种情况下,插入 sql 代码可以正常工作。

But you should generate a table with spring and insert data with a repository!但是您应该使用 spring 生成一个表,并使用存储库插入数据!

Repository for UserRole entity: UserRole 实体的存储库:

public interface UserRoleRepository extends CrudRepository<UserRole, Long> {}

After that just call the save method with the new instance of the entity in your service:之后,只需使用服务中实体的新实例调用 save 方法:

@AllArgsConstructor
@Service
public class YourService {

    private final UserRoleRepository userRoleRepository;

    public void exampleMethod() {
        final UserRole role = new UserRole();
        role.set("ADMIN");
        userRoleRepository.save(role);
    }
}

Last thing: dou you relly want to create table for roles?最后一件事:你真的想为角色创建表吗? I mean if users can create other roles then okay but if the roles are fix would be better just add role field to the user where the field type is enum which contains the user roles.我的意思是,如果用户可以创建其他角色,那么可以,但如果角色是固定的,那么只需将角色字段添加到字段类型为包含用户角色的枚举的用户即可。

public enum UserRole {
    ADMIN,
    USER
}

User entity with role field:具有角色字段的用户实体:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Enumerated(EnumType.STRING)
    private UserRole role;
}

Exception specifies that some problem with your SQL.异常指定您的 SQL 存在一些问题。

You have to specify that id should be incremented:您必须指定id应该递增:

CREATE TABLE IF NOT EXISTS opening_hour
(
    id    INT AUTO_INCREMENT PRIMARY KEY,
    role  VARCHAR(50)  null
);

Because later when the data is inserted, like:因为稍后插入数据时,例如:

INSERT INTO user_role (role) VALUES ('ADMIN'); INSERT INTO user_role (role) VALUES ('ADMIN');

You don't set id directly it should be auto-incremented by the DB engine.您不直接设置id它应该由数据库引擎自动递增。

Also, JPA API requires that your entities have to be serializable.此外, JPA API 要求您的实体必须是可序列化的。 You have to update it like following:你必须像下面这样更新它:

public class UserRole implements Serializable {
    private static final long serialVersionUID = 1L;

Probably for your purpose you select the easiest way to do this.可能出于您的目的,您 select 是执行此操作的最简单方法。

Much harder will be to use some migration applications like Flyway or Liquiebase and create some init script for this purpose.更难的是使用一些迁移应用程序,如FlywayLiquiebase ,并为此创建一些初始化脚本。

However, in this case, your DB interactions (like adding a new field to a class, thus updating the DB table respectively) should do it through adding a new migration script.但是,在这种情况下,您的 DB 交互(例如向 class 添加新字段,从而分别更新 DB 表)应该通过添加新的迁移脚本来完成。

Write it here, because it is too long to write it like a comment under the post.写在这里,因为太长了,写在帖子下像评论一样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring SQL:org.h2.jdbc.JdbcSQLSyntaxErrorException:SQL 语句中的语法错误“;预期为“标识符”,使用 INSERT INTO 时 - Spring SQL: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "; expected "identifier", when using INSERT INTO 如何修复 org.h2.jdbc.JdbcSQLSyntaxErrorException:SQL 语句中的语法错误需要“标识符” - How to fix org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement expected "identifier" Spring Data JPA @Query注释存在问题(SQL语法错误) - Problem with Spring Data JPA @Query Annotation (error in SQL syntax) JPA:Spring实体中的SQL语法错误 - JPA : Error in your SQL syntax in spring entity Spring Boot Data JPA NativeQuery 在 MySQL Workbench 中工作时抛出语法错误 - Spring Boot Data JPA NativeQuery throws Syntax-Error on Query working in MySQL Workbench 使用Flyway w / Spring Boot Test的H2 SQL语法错误`expected“。,COMMENT,(”` - H2 SQL Syntax Error `expected “., COMMENT, (”` using Flyway w/ Spring Boot Test Spring Boot数据JPA持久化到数据库错误 - Spring Boot data JPA persistence to database error 为什么会出现 SQL 语法错误? - 预期的“标识符”? - Why do I get SQL syntax error ? - expected "identifier"? Spring Boot,JPA错误:“通过JDBC语句执行DDL错误” - Spring Boot, JPA error: “Error executing DDL via JDBC Statement” 将 spring-boot-starter-parent 从 2.1.1 升级到 2.3.3 后 SQL 语句中的语法错误 - Syntax error in SQL statement after upgrading spring-boot-starter-parent from 2.1.1 to 2.3.3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM