当前位置: 首页 > 面试题库 >

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;
    }

    }

我正在使用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

请帮我解决一下这个。我是新来的hibernate并试图学习它。先感谢您。


问题答案:

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

示例:CREATE TABLE供应商(ID int NOT NULL AUTO_INCREMENT,PRIMARY KEY(ID))



 类似资料:
  • 我正在使用Hibernate在数据库中保存一个对象。我正在生成带有@GeneratedValue注释的主键。 这里是我试图将数据保存到数据库中的代码。 当我运行这个时,我得到以下错误

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

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

  • 问题内容: 是否有可能绕过Hibernate中的ID,在大多数情况下,我们希望使用来设置ID ,但在某些情况下希望手动设置ID。 这可能吗? 问题答案: 我知道您可以在JPA规范中执行此操作,因此您应该能够在Hibernate中(使用JPA +批注)。 如果仅填写要创建的新持久性模型的ID字段,那么当您将该模型“合并”到EntityManager中时,它将使用您设置的ID。 但是,这确实有后果。您

  • 我将web应用程序升级为使用Hibernate 4。在那之后,我遇到了一些问题,我需要帮助。 我有一个域对象的基类,如下所示: 然后,我有很多实体,比如: 我在实体之间有一些继承: 当我进行hql查询时,我得到了这个异常 在hibernate源代码中,我看到,如果实体的父级hibernate在默认情况下处于SINGLE\u表继承状态,那么在每个查询中,它将连接鉴别器列,但我没有鉴别器列,因为每个类

  • 嘿,我一直在尝试设置Hibernate Spatial来查询存储在PostGreSQL中的地理数据。我在尝试运行代码时收到以下错误。 SessionFactoryCreation的代码 如果我从依赖项和代码中删除Hibernate空间,它可以正常工作。但我真的需要使用空间,因为我的表包含纬度数据