【问题标题】:OneToMany Annotated Collection Not Persisting via HibernateOneToMany 带注释的集合不通过 Hibernate 持续存在
【发布时间】:2011-04-04 22:36:28
【问题描述】:

我目前正在尝试使用 @OneToMany(cascade=CascadeType.ALL) 为简单的对象列表保留一个集合。 Parent_Child 的表在 MySQL 中创建,但每个对象的键在使用 SaveOrUpdate 时不会更新。知道问题是什么吗? (定义了我的父键并生成了子键)。在坚持使用 saveOrUpdate 之前,我将子对象添加到父对象的集合中。我正在使用带有 hibernate 3 的 MySQL,并且我的 auto 属性设置为 create-drop。

测试类:

public class Tester {
    public static void main(String[] args) {
        VideoChannel testChannel = new VideoChannel("Test Channel");
        VideoChannelMap v = new VideoChannelMap(testChannel, "Test Map");
        VideoSource sc2Vid = new VideoSource("starcraft-ii-ghost-of-the-past.mp4", "EinghersStreamingBucket");
        testChannel.add(sc2Vid);
        Session s = HibernateSessionFactory.getSession();
        s.beginTransaction();
        s.saveOrUpdate(v);
        s.close();
    }           
}

实体:

@Entity
public class VideoChannelMap {
    @Id 
    String name;

    @OneToMany(cascade=CascadeType.ALL)
    List<VideoChannel> channelMap;

    public VideoChannelMap(VideoChannel initialVid, String name)
    {
        this.name = name;
        channelMap = new ArrayList<VideoChannel>();
        channelMap.add(initialVid);
        initialVid.setParent(this);
    }
}

@Entity
public class VideoChannel {

    @Id @GeneratedValue
    Long id;
    ...
}

【问题讨论】:

  • 实际代码不起作用将非常有助于缩小几十个潜在原因。

标签: java hibernate orm jpa


【解决方案1】:

您必须实际提交您的交易。当你关闭一个事务仍然打开的会话时的行为没有很好的定义,可能取决于你的数据库是如何在下面设置的。

Transaction t = s.beginTransaction();
s.saveOrUpdate(v);
t.commit();
s.close();

显然,对于“真实”代码,您还应该在其中进行一些 try-catch-finally 操作;)

【讨论】:

  • 提交交易确实有帮助。
猜你喜欢
  • 1970-01-01
  • 2016-01-04
  • 2014-09-07
  • 2016-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-11
相关资源
最近更新 更多