Hibernate 和 HSQLDB 违反主键完整性约束

Posted

技术标签:

【中文标题】Hibernate 和 HSQLDB 违反主键完整性约束【英文标题】:Primary key integrity constraint violation with Hibernate and HSQLDB 【发布时间】:2016-03-06 11:09:52 【问题描述】:

大家早上好

我在 Hibernate 中使用 HSQLDB。我有一种情况,即使我设置了主键值,我仍然得到一个integrity constraint violation: NOT NULL check constraint; SYS_CT_10346 table: NUMBERS column: PK。如下图所示。

SEVERE: integrity constraint violation: NOT NULL check constraint; SYS_CT_10346 table: NUMBERS column: PK
org.hibernate.exception.ConstraintViolationException: could not insert: [entity.Numbers]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638)
    at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)
    at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172)
    at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
    at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
    at dbconn.NumbersDB.saveNumbers(NumbersDB.java:75)
    at gui.UI.saveNumberStateButtonActionPerformed(UI.java:1807)
    at gui.UI.access$1800(UI.java:39)
    at gui.UI$20.actionPerformed(UI.java:788)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:688)
    at java.awt.EventQueue$3.run(EventQueue.java:686)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:702)
    at java.awt.EventQueue$4.run(EventQueue.java:700)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Caused by: java.sql.SQLIntegrityConstraintViolationException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10346 table: NUMBERS column: PK
    at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
    at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)
    ... 55 more

这是我的地图

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 22 Feb 2016 9:01:34 PM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
    <class name="entity.Numbers" table="NUMBERS" schema="PUBLIC" catalog="PUBLIC">
        <id name="pk" type="int">
            <column name="PK" />
            <generator class="native" />
        </id>
        <many-to-one name="account" class="entity.Account" fetch="select">
            <column name="ALLOCATEDACCOUNT"/>
        </many-to-one>
        <property name="number" type="string">
            <column name="NUMBER" length="25" not-null="true" />
        </property>
        <property name="allocated" type="boolean">
            <column name="ALLOCATED" not-null="true" />
        </property>
        <property name="alias" type="string">
            <column name="ALIAS" length="25" />
        </property>
        <property name="geographic" type="java.lang.Boolean">
            <column name="GEOGRAPHIC" />
        </property>
    </class>
</hibernate-mapping>

还有我的实体类

package entity;
// Generated 21 Feb 2016 1:44:55 AM by Hibernate Tools 3.2.1.GA

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * Numbers generated by hbm2java
 */
@Entity
@Table(name = "NUMBERS", schema = "PUBLIC", catalog = "PUBLIC")
public class Numbers implements java.io.Serializable 

    private Integer pk;
    private String number;
    private Account account;
    private boolean allocated;
    private String alias;
    private Boolean geographic;

    public Numbers() 
    

    public Numbers(Integer pk, String number, boolean allocated) 
        this.pk = pk;
        this.number = number;
        this.allocated = allocated;
    

    public Numbers(Integer pk, Account account, String number, boolean allocated, String alias, Boolean geographic) 
        this.pk = pk;
        this.account = account;
        this.number = number;
        this.allocated = allocated;
        this.alias = alias;
        this.geographic = geographic;
    

    @Id
    @Column(name = "PK", unique = true, nullable = false)    
    public Integer getPk() 
        return this.pk;
    

    public void setPk(Integer pk) 
        this.pk = pk;
    

    @Column(name = "NUMBER", nullable = false, length = 25)
    public String getNumber() 
        return this.number;
    

    public void setNumber(String number) 
        this.number = number;
    

    @Column(name = "ALLOCATED", nullable = false)
    public boolean isAllocated() 
        return this.allocated;
    

    public void setAllocated(boolean allocated) 
        this.allocated = allocated;
    

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ALLOCATEDACCOUNT")
    public Account getAccount() 
        return this.account;
    

    public void setAccount(Account account) 
        this.account = account;
    

    @Column(name = "ALIAS", length = 25)
    public String getAlias() 
        return this.alias;
    

    public void setAlias(String alias) 
        this.alias = alias;
    

    @Column(name = "GEOGRAPHIC")
    public Boolean getGeographic() 
        return this.geographic;
    

    public void setGeographic(Boolean geographic) 
        this.geographic = geographic;
    

最后是我要执行的代码

public boolean saveNumbers(Set numbersSet) 
        try 
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            for (Iterator<Numbers> it = numbersSet.iterator(); it.hasNext();) 
                Numbers numbers = it.next();
                if (numbers.getPk() == null) 
                    numbers.setPk(new Integer(5));
                    session.save(numbers);
                 else 
                    numbers = (Numbers) session.merge(numbers);
                    session.saveOrUpdate(numbers);
                
            
            session.getTransaction().commit();
            return true;
         catch (HibernateException he) 
            he.printStackTrace();
            return false;
        
    

session.save(numbers); 抛出异常

即使我手动设置主键,如上面的示例所示,它仍然会引发异常。 我试图设置如下所示的注释,但这仍然给了我同样的例外。

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "PK", unique = true, nullable = false)

非常感谢您的帮助

谢谢

【问题讨论】:

不要使用不必要的属性@Column(name = "PK", unique = true, nullable = false)@Id 表示它是独一无二的!我不确定nullable = false,但是对于生成的值,你也不需要它。 感谢您的建议,但即使取出 unique = true 它仍然会抛出相同的异常 不客气。当然,它不能修复错误。这只是一个建议。 你也不需要它@Basic(optional = false) 【参考方案1】:

大家早上好

因此,在经历了很多痛苦和磨难之后,问题的答案如下,在创建表时不要忘记将主键设置为 IDENTITY。谢谢大家的意见。

问候

布赖恩

【讨论】:

【参考方案2】:

您将相同的 PK 5 分配给尚未分配 PK 的所有实体。这意味着,您尝试使用完全相同的 PK 值保存所有新实例。

如果您使用生成的 ID,请不要为实体的 PK 字段分配任何内容。

【讨论】:

您好 感谢您抽出宝贵的时间来回答。我把它放进去是为了证明即使一个静态设置了一次,在一个空表上它仍然会抛出一个异常。问题是,即使我把它拿出来,我也会遇到这个理智的问题 然后将 PK 字段设置为可为空。异常谈论未通过的非空检查。您在 Numbers 的 PK 字段中从哪里获得 nullable=false ?它说从 hbm.xml 生成,但你没有改变它吗?还要检查 hbm.xml 或 annotations 哪个优先。 再次感谢您。当我生成 XML 时,我得到了 nullable = false。看到的实体代码是生成的,我一直在尝试更改它以使其正常工作。我所有的其他实体类都具有相同的注释,所以我对此感到非常沮丧。如何确定帽子优先? 尝试搜索您的版本的文档。但我仍然看到 hbm.XML 和您的注释之间存在不一致。您的注释中没有任何生成的 ID 规范。我建议仅使用 hbm.XML 或注释开始。你如何配置休眠?

以上是关于Hibernate 和 HSQLDB 违反主键完整性约束的主要内容,如果未能解决你的问题,请参考以下文章

简单的场景以“违反完整性约束”结束

Hibernate主键生成策略strategy = "increment"报错违反唯一性约束

ORA-02292违反完整约束和ORA-02297无法禁用约束条件 cascade禁用主键

Hibernate/H2 @OneToMany 删除子时“违反参照完整性约束”?

HSQLDB 内存设置的 HSQLDB 约束违规和 SQL 查询日志

Hibernate ORA-02292: 违反完整性约束 (ROOT.SYS_C007062) - 找到子记录