@ElementCollection用于持久保存Set <long>

时间:2018-09-28 03:34:03

标签: hibernate set

我的对象上有以下ElementCollection

public class MyObject {

@ElementCollection(targetClass=Long)
Set<Long> otherIds

}

这应该创建一个具有值的表

myObj_id   other_id
1            2
1            3
2            4
3            4

但是它只会创建下面的行

 myObj_id   other_id
    1            2
    1            3
    2            4

有些事情让我觉得在other_id列中不允许重复值'4' 但我不确定为什么,我尝试了以下方法

  • 在关闭会话前刷新会话
  • 提交交易
  • 使用cascadeType SAVE_UPDATE
  • 尝试使用列表代替Set
  • 尝试设置FetchType.EAGER

    我错过了什么?

这是保存代码

public MyObj createOrSave(MyObj obj) {
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {


      session.beginTransaction();
      session.saveOrUpdate(obj);
      session.getTransaction().commit();
    } catch (RuntimeException e) {

      session.getTransaction().rollback();
      throw e;
    } finally {
      if (session != null && session.isOpen()) {
        session.close();

      }
    }

    return obj;
  }

看看表结构,这会同时创建myObj_id和other_id作为主键,这是问题吗?

我添加了更多日志,看起来,就在第二次保存实体之前,other_id的ID为null。不知道那是什么意思,但看起来很奇怪

0 个答案:

没有答案