Hibernate:使用复杂对象的集合会抛出异常

时间:2011-09-29 20:35:46

标签: java mysql hibernate java-ee hibernate-mapping

我正在研究Hibernate并存储复杂类型的集合。但我遇到了异常。

我有以下持久类:

public class Item {

    private Long id;
    private Set images = new HashSet();
    private Collection<Data> data = new ArrayList<Data>();

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public Set getImages() {
        return images;
    }
    public void setImages(Set images) {
        this.images = images;
    }
    public Collection<Data> getData() {
        return data;
    }
    public void setData(Collection<Data> data) {
        this.data = data;
    }
}

数据类如下:

public class Data {

  private String firstName;
  private String lastName;
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;     
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  @Override
   public boolean equals(Object obj) {
    if(!(obj instanceof Data) )
        return false;
    Data d = (Data) obj;
    if(d.firstName.equals(firstName) && d.lastName.equals(lastName))
        return true;
    return false;
  }
 @Override
 public int hashCode() {
    int result;
    result = 17;
    result = 31 * result + firstName.hashCode();
    result = 31 * result + lastName.hashCode();
    return result;
}

映射文件如下:
对于项目类:

<hibernate-mapping>
    <class name="com.entities.Item" table="ITEM">
        <id name="id" type="java.lang.Long">
            <column name="ID" />
            <generator class="identity" />
        </id>
        <set name="images" table="ITEM_IMAGE" inverse="false" lazy="true">
            <key>
                <column name="ID" />
            </key>
            <element type="string">
                <column name="IMAGES" />
            </element>
        </set>
        <bag name="data" table="DATA" inverse="false" lazy="true">
            <key>
                <column name="ID" />
            </key>
            <one-to-many class="com.entities.Data" />
        </bag>
    </class>
</hibernate-mapping>

对于数据类:

<hibernate-mapping>
    <class name="com.entities.Data" table="DATA">    
        <id name="firstName" type="java.lang.String">
            <column name="FIRSTNAME" />
            <generator class="assigned" />
        </id>
        <property name="lastName" type="java.lang.String">
            <column name="LASTNAME" />
        </property>
    </class>
</hibernate-mapping>

在我的代码中将数据保存到MySQL:

Transaction tx = session.beginTransaction();
Item item = new Item();
Set images = new HashSet();
images.add("C:\\");
images.add("D:\\");
item.setImages(images);
List<Data> data = new ArrayList<Data>();
Data a = new Data();
a.setFirstName("John");
a.setLastName("Smith");
data.add(a);
item.setData(data);
session.save(item);
tx.commit();//-->Exception here
session.close();

我在tx.commit();

上收到以下异常
  

Hibernate:插入ITEM值()Hibernate:插入   ITEM_IMAGE(ID,IMAGES)值(?,?)Hibernate:插入   ITEM_IMAGE(ID,IMAGES)值(?,?)Hibernate:更新数据集ID =?   FIRSTNAME =? Hibernate:更新DATA set ID =? FIRSTNAME =?   1454 [main] ERROR org.hibernate.jdbc.AbstractBatcher - Exception   执行批处理:org.hibernate.StaleStateException:批量更新   从update [0]返回意外的行数;实际行数:0;   预计:1点   org.hibernate.jdbc.Expectations $ BasicExpectation.checkBatched(Expectations.java:85)     在   org.hibernate.jdbc.Expectations $ BasicExpectation.verifyOutcome(Expectations.java:70)     在   org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:90)     在   org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)     在   org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)     在   org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)     在   org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:188)     在   org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)     在   org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)     在org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)at   org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)at   org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)     在com.entities.Main.main(Main.java:44)

为什么我会得到这个例外?
如果我删除Collection<Data> data只存储Set代码有效,数据保存在MySQL中。

注意:映射文件是由Eclipse Hibernate插件创建的。

2 个答案:

答案 0 :(得分:1)

对您的代码进行了以下更改:

Transaction tx = session.beginTransaction();
Item item = new Item();
//added save here to attach the object to persistance context.
// (This might be optional)
session.save(item);              

Set images = new HashSet();
images.add("C:\\");
images.add("D:\\");
item.setImages(images);           
List<Data> data = new ArrayList<Data>();
Data a = new Data();
a.setFirstName("John");
a.setLastName("Smith");
//added save here to attach the object to persistance context.
//this is required without cascading settings
session.save(a)                 

data.add(a);
item.setData(data);
session.save(item);
tx.commit();//-->Exception here
session.close();

您可以另外设置 相应的 包上的级联选项!

AFAIK您收到错误,因为您尝试在没有其他实体(Data)处于持久状态的情况下持久保存关联,并且默认情况下级联选项设置为none。我还没有尝试过运行我的片段,但这会指向正确的方向。


来自OP的更新:

使用inverse="true"来解决问题,执行cascade,我必须从Data引用Item,否则FK列不会更新

答案 1 :(得分:0)

是否可能是因为您将a添加到列表data两次?