Hibernate的麻烦:INSERT,而不是使用UPDATE时继承:SINGLE_TABLE和Se

2019-08-16 18:05发布

我一直在使用实现继承层次SINGLE_TABLE与SecondaryTables 。

这工作,否则,但是当我的副表的字段(一个或多个)是空的(=在甲骨文空),下一次更新的实体因为Hibernate认为它应该INSERT表时,应该更新失败。 例:

CREATE TABLE TASK 
(
   ID NUMBER(10) NOT NULL 
   , TYPE NUMBER(1) NOT NULL 
   , STATUS NUMBER(1) NOT NULL 
, CONSTRAINT TASK_PK PRIMARY KEY  (ID) ENABLE);

CREATE TABLE SUB_TASK 
(
  ID NUMBER(10) NOT NULL 
, TEXT VARCHAR2(4000 CHAR) 
, CONSTRAINT SUB_TASK_PK PRIMARY KEY 
(ID) ENABLE);

ALTER TABLE SUB_TASK
ADD CONSTRAINT SUB_TASK_FK1 FOREIGN KEY
(ID)REFERENCES TASK(ID)ENABLE;

Task.java:

@Entity
@Table(name="TASK")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE",discriminatorType=DiscriminatorType.INTEGER)
public abstract class Task implements Serializable, Comparable<Task> {

@Id
@Column(nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TASK_GEN")
@SequenceGenerator(name = "TASK_GEN", sequenceName = "SEQ_TASK", allocationSize = 1)
private Long id;

@Column(name = "TYPE", nullable = false, insertable=false, updatable=false)
private int typeCode;

SubTask.java

@Entity
@DiscriminatorValue("7")
@SecondaryTable(name = "SUB_TASK", pkJoinColumns = {@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")})
public class SubTask extends Task implements Serializable {

@Column(name="TEXT", length = 4000, table="SUB_TASK")
@Size(max = 4000)
private String text;

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

}

节约而先前空SubTask.text实体时异常:

org.hibernate.exception.ConstraintViolationException:ORA-00001:一个是约束侵犯的概念(SUB_TASK_PK)所造成

at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:128)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at $Proxy75.executeUpdate(Unknown Source)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2965)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3028)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3350)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:140)

我调试相关Hibernate代码,AbstractEntityPersister.java:

    if ( !isInverseTable( j ) ) {

        final boolean isRowToUpdate;
        if ( isNullableTable( j ) && oldFields != null && isAllNull( oldFields, j ) ) {
            //don't bother trying to update, we know there is no row there yet
            isRowToUpdate = false;
        }
        else if ( isNullableTable( j ) && isAllNull( fields, j ) ) {
            //if all fields are null, we might need to delete existing row
            isRowToUpdate = true;
            delete( id, oldVersion, j, object, getSQLDeleteStrings()[j], session, null );
        }
        else {
            //there is probably a row there, so try to update
            //if no rows were updated, we will find out
            isRowToUpdate = update( id, fields, oldFields, rowId, includeProperty, j, oldVersion, object, sql, session );
        }

        if ( !isRowToUpdate && !isAllNull( fields, j ) ) {
            // assume that the row was not there since it previously had only null
            // values, so do an INSERT instead
            //TODO: does not respect dynamic-insert
            insert( id, fields, getPropertyInsertability(), j, getSQLInsertStrings()[j], object, session );
        }

    }

它看起来像第一个if(“不打扰试图更新”)完成和isRowToUpdate =假,最后如果(如果(!isRowToUpdate &&!isAllNull(场,J))也做了,使插入被执行。

我想我可以解决这个问题加上空非空田头到餐桌SUB_TASK,但是这是我唯一的选择吗?

使用Hibernate 4.17.final

编辑:有希望的清晰度我在做什么:

SubTask s = taskRepository.findOne(42l);
s.setText("dasdsa");
taskRepository.save(s); // OK
s.setText(null); 
taskRepository.save(s); // OK
s.setText("update after null value");
taskRepository.save(s); // exception 

我使用Spring的数据持久性,但(使用香草JPA的时候,我会承担同样的事情发生),它看起来并不像问题与它

Answer 1:

我有一个有点类似的问题,具有@ManyToOne在二次表定义的关系。 当二次表有一个行指的是在主表中的实体,关系柱空,并试图设置一个值时,Hibernate试图插入,而不是更新现有的一个新行,抛出一个约束违反异常。

解决的办法是使用注释@org.hibernate.annotations.Table(appliesTo="secondary_table", optional=false) ,这使得休眠更新的行。

我不确定有关的行为当副表doesn't行存在,但也许它解决您的问题。



Answer 2:

使用@dampudia解决方案为我工作。

请确保添加在主表上,而不是次要表如下。 另外,请注意这里使用@Table注解是从休眠状态而不是java.persistence。

@ org.hibernate.annotations.Table(appliesTo = “secondary_table”,可选=假)



文章来源: Hibernate trouble: INSERT instead of UPDATE when using Inheritance:SINGLE_TABLE and SecondaryTables