@ElementCollection未由Hibernate 4.0.1保存

时间:2012-01-22 22:21:44

标签: spring-3 hibernate-4.x

我有类(实体)A,其中包含包含B的对象(实体)Set<String> strings列表。

@Entity
@Table(name = "a")
public class A {

    private int id;
    private List<B> bList;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "aId")
    public int getId() {
        return id;
    }

    @OneToMany(fetch = FetchType.EAGER)
    @JoinColumn(name = "aId", nullable = false)
    @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
    public List<B> getBList() {
        return bList;
    }
    ... setters and other stuff
}

@Entity
@Table(name = "b")
public class B {

    private int id;
    private int aId;
    private Set<String> strings;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "bId")
    public int getId() {
        return id;
    }

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "b_strings", joinColumns = {@JoinColumn(name = "bId")})
    @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})**
    public Set<String> getStrings() {
        return strings;
    }

    @Column(name = "aId", insertable = false, updatable = false)
    public int getAId() {
        return aId;
    }
    ... setters and other stuff
}

我创建了对象A,然后我尝试保存它:

A a = new A();
List<B> l = new ArrayList<B>();
a.setBList(l);
B b = new B();
l.add(b);
b.setStrings(new HashSet<String>());
b.getStrings().add("1");
b.getStrings().add("2");

b = new B();
l.add(b);
b.setStrings(new HashSet<String>());
b.getStrings().add("3");

Session session = sessionFactory.openSession();
session.saveOrUpdate(a);
session.close();
保存(插入)了

AB对象,但未保存使用strings设置的对象。我正在使用Spring 3.1和Hibernate 4.0.1。为什么hibernate会忽略@ElementCollection?创建表,mysql workbech将其显示为只读...

1 个答案:

答案 0 :(得分:1)

映射是可以的。我是盲人,session.beginTransaction();和session.getTransaction()。commit();保存对象时丢失了。