繁体   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