gpt4 book ai didi

java - 如何使用java + hibernate将值插入SQL Server中的主键?

转载 作者:太空宇宙 更新时间:2023-11-04 09:25:23 25 4
gpt4 key购买 nike

尝试使用 hibernate 运行此 java 代码时收到此错误消息:

create table EMPLOYEE (
ID integer not null,
JOINING_DATE date not null,
NAME varchar(50) not null,
SALARY decimal(10,2) not null,
SSN varchar(255) not null,
primary key (ID)
)

我的Java代码如下所示,使用hibernate,我需要将值插入数据库。

@Entity
@Table(name="EMPLOYEE")
public class Employee {

@Id
@Column(name = "ID", nullable = false, insertable = false, updatable = false)
@TableGenerator(name="ID" ,table="EMPLOYEE", allocationSize=1, initialValue=1)
private int id;

@Size(min=3, max=50)
@Column(name = "NAME", nullable = false)
private String name;

但是在插入值时出现以下错误:

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
com.microsoft.sqlserver.jdbc.SQLServerException: Violation of PRIMARY KEY constraint 'PK__EMPLOYEE__3214EC27B6653156'. Cannot insert duplicate key in object 'dbo.EMPLOYEE'. The duplicate key value is (0).
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1493)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:390)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:340)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1400)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:179)
at

最佳答案

创建表时,您应指示 ID 列是主键,并且数据库应控制分配该值:

 id integer NOT NULL IDENTITY PRIMARY KEY,

我对@TableGenerator注解不太熟悉,更常见的方法是用以下方式注解id字段:

@GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)

IDENTITY Indicates that the persistence provider must assign primary keys for the entity using a database identity column. More information...

从而让Hibernate知道该字段的值是由数据库控制的。

我希望这会有所帮助。

关于java - 如何使用java + hibernate将值插入SQL Server中的主键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57760395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com