簡體   English   中英

如何使用Java + Hibernate在SQL Server的主鍵中插入值?

[英]How to insert value into primary key in SQL server by using java + 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代碼,並使用休眠模式,我需要在DB中插入值。

@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指示持久性提供程序必須使用數據庫標識列為實體分配主鍵。 更多信息...

因此,讓Hibernate知道該字段的值是由數據庫控制的。

我希望這有幫助。

@TableGenerator的文檔說:

定義一個主鍵生成器,當為GeneratedValue批注指定了生成器元素時,可以按名稱引用。

這意味着id字段應該另外具有@GeneratedValue注釋,例如@TableGenerator(name =“ myTableGen ”,table =“ xxx”, locationSize = 1,initialValue = 1)@GeneratedValue(strategy = TABLE,generator =“ myTableGen ”)

因此,@ TableGenerator的屬性可以解釋如下:name:唯一的生成器名稱,可以由一個或多個類引用以作為id值的生成器。 table:存儲主鍵值的表pkColumnName:表中存儲主鍵值的列...

參考是 https://docs.oracle.com/javaee/7/api/javax/persistence/TableGenerator.html

但是@TableGenerator意味着將使用一個單獨的表來保存生成的ID。 如果您不希望這種開銷,而只想在ID列中生成值,則可以使用其他生成器類型,例如Sequence或Identity

嘗試使用

private Integer id;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM