简体   繁体   English

Spring 进口 SQL 与 Hibernate

[英]Spring import SQL with Hibernate

I want to use Hibernate when running the initial sql file.我想在运行初始 sql 文件时使用 Hibernate 。 The problem I currently have is that I get the following Exception: I want HIBERNATE to insert the ID instead of the database!我目前遇到的问题是我得到以下异常:我希望 HIBERNATE 插入 ID 而不是数据库!

Caused by: java.sql.SQLException: Field 'id' doesn't have a default value

My application.properties looks like this:我的 application.properties 看起来像这样:

spring.jpa.database-platform=org.hibernate.dialect.MariaDBDialect
#Data Source Settings
spring.datasource.url=jdbc:mariadb://localhost:3306/kotlin
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.dbcp2.test-while-idle=true
spring.datasource.dbcp2.validation-query=SELECT 1
spring.datasource.continue-on-error=false
#Add Initial Date for Testing
spring.datasource.initialization-mode=always
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.hbm2ddl.import_files=data.sql

My User Model contains:我的用户 Model 包含:

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
var id: Long = 0

My startup sql script:我的启动 sql 脚本:

INSERT INTO user (first_name, last_name, pass_word, user_name, version, email) VALUES ('deepak', 'sp', '$2a$10$2nU5xMCyzPMeNiGQsrjzQeWNcHf9NjtGzVFgy6kVRcZlLh/ABTgZW', 'spdeepak', 1, "example@example.com");

It seems like it wants to directly execute the sql (generated ID by Hibernate is not used) instead of creating an User-object and afterwards insert the data.似乎它想直接执行 sql (不使用由 Hibernate 生成的 ID)而不是创建用户对象然后插入数据。

I ALSO get this error when dealing with default values (It says there is no default value on database).在处理默认值时,我也会收到此错误(它说数据库上没有默认值)。 So please don't just answer with "Use GenerationType.IDENTITY)所以请不要只回答“使用GenerationType.IDENTITY)

Try this:尝试这个:

INSERT INTO user (id, first_name, last_name, pass_word, user_name, version, email) 
VALUES 
(null, 'deepak', 'sp', '$2a$10$2nU5xMCyzPMeNiGQsrjzQeWNcHf9NjtGzVFgy6kVRcZlLh/ABTgZW', 'spdeepak', 1, "example@example.com");

Your insert statement is missing id column, but it is required.您的插入语句缺少 id 列,但它是必需的。 If you provide null value, then db will assign its value automatically by usign autoincrement.如果您提供 null 值,则 db 将通过 usign autoincrement 自动分配其值。

About id generation by hibernate for manual scripts - it is impossible.关于 hibernate 为手动脚本生成 id - 这是不可能的。 Manual scripts are executed as is directly to the database without any framework.手动脚本按原样直接执行到数据库,无需任何框架。 It is pure jdbc statement sql script execution.它是纯 jdbc 语句 sql 脚本执行。

I see that your are using jpa repositories according to your properties files.我看到您正在根据您的属性文件使用 jpa 存储库。 If you want id generation to be made by hibernate then you should create your user through jpa repository.如果您希望通过 hibernate 生成 id,那么您应该通过 jpa 存储库创建您的用户。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM