使用现有数据使用 JPA 创建 POST

Make a POST with JPA with existing data

我有以下问题,问题是我有一个实体:

package com.innovart.cpve.user.persistence.entity;

import lombok.Data;

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
@Data
@Table(name = "CPVE_USERS")
public class User {

@Id
@Column(name = "IDUSERS")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long idUser;

@Column(name = "IDROLES")
private Long idRol;

@Column(name = "USERNAME")
private String username;

@Column(name = "EMAIL")
private String email;

@Column(name = "PHONE")
private String phone;

@Column(name = "NAME")
private String name;

@Column(name = "LAST_NAME")
private String lastName;

@Column(name = "PASSWORD")
private String password;

@Column(name = "COUNTRY")
private String country;

@Column(name = "CITY")
private String city;

@Column(name = "GRANTS")
private String grant;

@Column(name = "STATE_ACTIVE")
private Integer stateActive;

@Column(name = "REGISTRATION_DATE")
private LocalDateTime registrationDate;

}

问题是这个后台连接到一个 Oracle 数据库,我已经有几个注册用户,但这些是通过 Mockaroo 脚本输入的,当我尝试通过服务 Rest 保存新用户时抛出这个错误:

2021-12-22 11:03:53.156 ERROR 23148 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[. 
[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context 
with path [/api] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

oracle.jdbc.OracleDatabaseException: ORA-01400: cannot insert NULL into ("CPVE"."CPVE_USERS"."IDUSERS")

当然我知道问题是因为我已经创建了记录,Spring 尝试创建一个新用户,但它“不知道”它必须从 PK 500 开始,例如.

难道有什么方法可以让Spring自动知道用户PK去哪的数据,然后继续吗?

这看起来字段 idUser 为空。 确保的一种方法是在插入之前将 Use.idUser 设置为某个值,以查看问题是否再次发生

问题是,当使用“策略 = GenerationType.AUTO”时,Hibernate 在我的 Oracle 数据库中创建了一个名为 Hibernate_Sequence 的序列,它定义了“idUsers”的值是多少,我决定在示例中创建您自己的序列以从我决定的值中获取计数。

@Id
@Column(name = "IDUSERS")
@GeneratedValue(
        strategy = GenerationType.SEQUENCE,
        generator = "sequence-generator"
)
@SequenceGenerator(
        name = "sequence-generator",
        sequenceName = "SEC_IDUSER",
        initialValue = 501,
        allocationSize=1
)
private Long idUser;

这就是我的实体代码的外观,如果它已经允许我保存新用户的话。 <3 <3 <3 <3 非常感谢大家。