当前位置: 首页 > 知识库问答 >
问题:

主键的Hibernate@GeneratedValue为空错误

杨超
2023-03-14

我正在使用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;
    }
        
    }
vendor_ID   int         Unchecked -------> Primary key
vname       varchar(50) Checked
phone_no    bigint      Checked
emailID     varchar(50) Checked
updated     bit         Checked

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

@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个答案

柯新翰
2023-03-14

如果您使用@GeneratedValue的javax.persistence.GenerationType.identity策略,那么您的表必须有一个标识生成器。这可以通过对主键使用AUTO_INCREMENT来完成。

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

 类似资料:
  • 问题内容: 我正在使用Hibernate将对象保存在数据库中。我正在使用@GeneratedValue注释生成主键。 这是我的代码供应商类 我正在使用MS SQL Server 2012,其中有带有以下列的供应商表 未选中表示其NOTNULL = true,不允许使用空值。 这是我试图将数据保存到数据库中的代码。 运行此命令时,出现以下错误 请帮我解决一下这个。我是新来的hibernate并试图学

  • 问题内容: 对于映射到HSQLDB中的表的实体中的id字段,我具有以下定义。 但这似乎不会生成唯一的ID。而是尝试将null插入列中,这将导致失败。如果我手动创建一个序列和生成策略以使用该序列,那么数据将按预期持久保存。 自动生成策略不是暗示提供者(在这种情况下为hibernate)将自动选择正确的方法并根据需要进行所有繁重的工作(创建序列,使用本机方法或适用于该特定平台的任何方法)吗?我的理解不

  • 我有一个复合主键,其中一个键为空。实体中必须存在哪些注释,以便我可以使用此类JPA获取数据: 我尝试使用IdClass Annotation和EmbeddedId Annotation,但出现异常: 例如,使用了数据,但在实际项目中使用了类似的数据,因此无法用值替换null。

  • 我是PostGIS的新手,我正在使用带有Hibernate Spatial和Spring框架的PostGIS。问题是主键没有自动设置,在将数据插入数据库时,我收到以下错误: 我已经在MySQL上测试了代码,它工作正常。但是,当使用Hibernate Spatial和PostGIS时,它会给我提到的错误。模型如下: 以下是插入数据的代码: 以下是Maven中的依赖项: 和Hibernate配置: 我

  • 例如,如果我希望生成的ID开始为100,XXX而不是10,XXX并增加100,我将如何进行更改? 请帮个忙。提前谢了。

  • 问题内容: 我必须使用hibernate模式,并且不太确定如何解决此问题,我有2个具有1..n关系的表,如下所示: 我该如何使用Hibernate进行管理??? 我不知道如何管理第二张表的主键… 问题答案: 在Hibernate参考文档中有一个与您的案例完全相似的示例。在此示例之前,您将找到解释。这是与您的问题匹配的示例(用户是表A,客户是表B): 注意:如果您拥有这两个表的代理标识符,则要简单得