主键的休眠@GeneratedValue null 错误

Posted

技术标签:

【中文标题】主键的休眠@GeneratedValue null 错误【英文标题】:Hibernate @GeneratedValue null error for primary key 【发布时间】:2015-12-09 06:48:39 【问题描述】:

我正在使用 Hibernate 在数据库中保存一个对象。我正在使用 @GeneratedValue 注释生成我的主键。

这是我的代码供应商类

  package com.samples.vendor;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;


@Entity
@Table(name = "Vendor")
public class Vendor implements Serializable 

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
    @Column(name="vendor_ID", unique = true, nullable = false)
    private int vendor_ID;
    private String vname;
    private long phone_no;
    private String emailID;
    @Transient
    private int updated;
    
    
    public int getVendor_ID() 
        return vendor_ID;
    
    public void setVendor_ID(int vendor_ID) 
        this.vendor_ID = vendor_ID;
    
    public String getVname() 
        return vname;
    
    public void setVname(String vname) 
        this.vname = vname;
    
    public long getPhone_no() 
        return phone_no;
    
    public void setPhone_no(long phone_no) 
        this.phone_no = phone_no;
    
    public String getEmailID() 
        return emailID;
    
    public void setEmailID(String emailID) 
        this.emailID = emailID;
    
    public int getUpdated() 
        return updated;
    
    public void setUpdated(int updated) 
        this.updated = updated;
    
        
    

我正在使用 MS SQL Server 2012,其中我有一个包含以下列的供应商表

vendor_ID   int         Unchecked -------> Primary key
vname       varchar(50) Checked
phone_no    bigint      Checked
emailID     varchar(50) Checked
updated     bit         Checked

未选中意味着它的NOTNULL = true,它不允许空值。

这是我试图将数据保存到数据库中的代码。

@RequestMapping(value = "addVendor", method = RequestMethod.POST)
public ModelAndView addVendor(@ModelAttribute("vendor") Vendor vendor, BindingResult result)

    if(result.hasErrors())
    
        ModelAndView modelErr = new ModelAndView("AddVendor");
        return modelErr;
    
    Session session = null;
    try
    
    
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(vendor);
        session.getTransaction().commit();
        
        ModelAndView modelview = new ModelAndView("Insert");
        return modelview;
    
    
    catch(Exception ex)
    
        ex.printStackTrace();
    
    finally
    
        session.close();
    
    return null;

当我运行它时,我得到以下错误

 Hibernate: insert into Vendor (emailID, phone_no, vname) values (?, ?, ?)
Sep 12, 2015 7:45:53 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 515, SQLState: 23000
Sep 12, 2015 7:45:53 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Cannot insert the value NULL into column 'vendor_ID', table 'VendorCalls.dbo.Vendor'; column does not allow nulls. INSERT fails.
org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:84)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2730)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3300)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:474)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:179)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:163)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:198)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:317)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:272)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:178)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:109)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:678)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:670)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:665)
    at com.samples.vendor.InsertDB.addVendor(InsertDB.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL into column 'vendor_ID', table 'VendorCalls.dbo.Vendor'; column does not allow nulls. INSERT fails.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:314)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
    ... 59 more

【问题讨论】:

【参考方案1】:

如果您对@GeneratedValue 使用策略 javax.persistence.GenerationType.IDENTITY,则您的表必须具有标识生成器。这可以在您的主键中包含一个 AUTO_INCREMENT。

示例: 创建表供应商 ( ID int NOT NULL AUTO_INCREMENT, 主键 (ID) )

【讨论】:

当我们使用@GeneratedValue注解时,hibernate不会自己生成一个标识值吗?我的理解是我可以将数据库中的列更改为 IDENTITY 并且可以取消 AUTO_INCREMENT 对吗? 不一定,只是尝试了一个带有 (strategy = GenerationType.IDENTITY) 的实体,它是没有 AUTO_INCREMENT 的表。 Hibernate 向我返回了一个错误,说该实体的 ID 没有错误默认值。包含 AUTO_INCREMENT 后一切正常。【参考方案2】:

您的vendor_ID 没有默认值,但它有NOT NULL 约束。当你在做INSERT时,你必须设置vendor_ID,或者如果你不想手动设置,那么你应该设置AUTO_INCREMENT属性来为新行生成一个唯一的标识。请记住,如果您没有为 id 字段设置任何值,则它应该为 null 或默认值(或者如果您设置该属性,它将自动递增)。

@GeneratedValue 注释只是告诉 Hibernate 数据库正在自己生成这个值。所以AUTO_INCREMENT也应该在数据库中定义。

【讨论】:

成功了。我唯一需要做的就是在列中添加标识。谢谢【参考方案3】:

我不知道 Hibernate ORM 是否更新了那么多,但目前如果使用 @GeneratedValue,则必须省略装饰器 @Column()

所以你的代码将是

@Id
@GeneratedValue
private int vendor_ID;

而不是

@Id
@GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
@Column(name="vendor_ID", unique = true, nullable = false)
private int vendor_ID;

希望对你有帮助。

【讨论】:

以上是关于主键的休眠@GeneratedValue null 错误的主要内容,如果未能解决你的问题,请参考以下文章

休眠仅保存具有复合主键中的父外键的子表条目

JPA之@GeneratedValue注解(转)

JPA注解

休眠:外键的列数错误

JPA Hibernate 使用UUID做为主键的问题

JPA注解主键生成策略-UUID