在H2中与Generatype.Identity& schema.sql- Springboot

发布于 2025-02-12 17:51:23 字数 3391 浏览 0 评论 0原文

我正在尝试使用 schema.sql 来创建和预紧嵌入H2 DB 。但是,一旦我尝试使用POST请求添加新用户,就会发生以下错误。

2022-07-04 23:35:53.153错误8180 --- [NIO-8080-EXEC-2] oaccc [。[。[/]。 在路径上[] [请求处理失败;嵌套异常是 org.springframework.dao.DaintegrityVioLationException:不能 执行语句; sql [n/a];约束[“主键 public.users(user_id)(/ *键:1 */1,'mrxxx',' [电子邮件 受保护] ', '123456'); sql语句:插入用户(user_id,电子邮件, USER_NAME,密码)值(默认,?,?,?)[23505-214]];嵌套 异常是org.hibernate.exception.constraintviolationException: 无法执行语句]用根本原因

org.h2.h2.jdbc.jdbcsqlintegritycontectrationcontaintviolationException:唯一索引 或主要密钥违规:“ public.users上的主要密钥(user_id)( /*) 键:1 */1,'mrxxx',' ','123456')“; sql 陈述: 插入用户(user_id,email,user_name,密码)值 (默认,?,?,?)[23505-214]

我想这是因为 @generatedValue(stragity = generationType.Identity)正在尝试创建user_id = 1,但它已经存在于db中正如我们预装的那样。我不知道如何摆脱它

request

{
    "name" : "Arunkumar",
    "email" : "[email protected]",
    "password" : "arun1234" 
}

响应

{
    "timestamp": "2022-07-04T18:05:53.184+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "path": "/post"
}

上找到代码段

请在 application.properties

spring.jpa.hibernate.ddl-auto=none
spring.datasource.initialization-mode=always

spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name= org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

schema.sql

DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (
  `user_id` int NOT NULL AUTO_INCREMENT,
  `user_name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `password` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
);

INSERT INTO `users` VALUES (1,'mrxxx', '[email protected]', '123456');

users.java

@Entity
public class Users {    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="USER_ID")
    private int id;
    @Column(name="USER_NAME")
    private String name;
    @Column(name="PASSWORD")
    private String password;
    @Column(name="EMAIL")
    private String email;
    .......
}

dbcotroller.java

@RestController
public class DbController {

    @Autowired
    private DbRepo userRepo;
    
    @PostMapping("/post")
    public ResponseEntity<?> saveUser(@RequestBody Users user){
        userRepo.save(user);
        return new ResponseEntity<>(user, HttpStatus.CREATED);
    }
}

I am trying to create and preload embedded H2 Db with some data using schema.sql. But once I try to add new user using POST request, the following error occurs.

2022-07-04 23:35:53.153 ERROR 8180 --- [nio-8080-exec-2]
o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for
servlet [dispatcherServlet] in context with path [] threw exception
[Request processing failed; nested exception is
org.springframework.dao.DataIntegrityViolationException: could not
execute statement; SQL [n/a]; constraint ["PRIMARY KEY ON
PUBLIC.USERS(USER_ID) ( /* key:1 */ 1, 'mrxxx', '[email protected]',
'123456')"; SQL statement: insert into users (user_id, email,
user_name, password) values (default, ?, ?, ?) [23505-214]]; nested
exception is org.hibernate.exception.ConstraintViolationException:
could not execute statement] with root cause

org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index
or primary key violation: "PRIMARY KEY ON PUBLIC.USERS(USER_ID) ( /*
key:1 */ 1, 'mrxxx', '[email protected]', '123456')"; SQL statement:
insert into users (user_id, email, user_name, password) values
(default, ?, ?, ?) [23505-214]

I guess this is happening because the @GeneratedValue(strategy = GenerationType.IDENTITY) is trying to create user_id = 1 but it already exists in Db as we have preloaded it. I dont know how to get rid of it

Request

{
    "name" : "Arunkumar",
    "email" : "[email protected]",
    "password" : "arun1234" 
}

Response

{
    "timestamp": "2022-07-04T18:05:53.184+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "path": "/post"
}

Please find the code snippets below

application.properties

spring.jpa.hibernate.ddl-auto=none
spring.datasource.initialization-mode=always

spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name= org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

schema.sql

DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (
  `user_id` int NOT NULL AUTO_INCREMENT,
  `user_name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `password` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
);

INSERT INTO `users` VALUES (1,'mrxxx', '[email protected]', '123456');

Users.java

@Entity
public class Users {    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="USER_ID")
    private int id;
    @Column(name="USER_NAME")
    private String name;
    @Column(name="PASSWORD")
    private String password;
    @Column(name="EMAIL")
    private String email;
    .......
}

DbCotroller.java

@RestController
public class DbController {

    @Autowired
    private DbRepo userRepo;
    
    @PostMapping("/post")
    public ResponseEntity<?> saveUser(@RequestBody Users user){
        userRepo.save(user);
        return new ResponseEntity<>(user, HttpStatus.CREATED);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神经暖 2025-02-19 17:51:23

您可以省略插入查询中的ID:

INSERT INTO `users`(`USER_NAME`,`EMAIL`,`PASSWORD`) VALUES ('mrxxx', '[email protected]', '123456');

You can omit the id in the insert query:

INSERT INTO `users`(`USER_NAME`,`EMAIL`,`PASSWORD`) VALUES ('mrxxx', '[email protected]', '123456');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文