开发者

TABLE_PER_CLASS Bidirectional @OneToMany Problem

开发者 https://www.devze.com 2023-02-16 05:44 出处:网络
Hibernate can do bidirectional polymorphism with TABLE_PER_CLASS (<union-subclass>), says so here:

Hibernate can do bidirectional polymorphism with TABLE_PER_CLASS (<union-subclass>), says so here:

This strategy supports one-to-many associations provided that they are bidirectional.

I'm trying to get a simple example to work. 4 basic classes: abstract A <-- B <-- C and A <-- D, where D is holding myArray of B's.

I get no error; myArray is simply empty.

Details

A

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Class_A {开发者_运维问答
    @Id
    public int myId = 0;
    public int a = 0;
}

B

@Entity
public class Class_B extends Class_A {
    public int b = 0;

    @ManyToOne
    @JoinColumn(name="join_column_b")
    private Class_D class_d;
}

C

@Entity
public class Class_C extends Class_B {
    public int c = 0;
}

D

@Entity
public class Class_D extends Class_A {
    @OneToMany(cascade=CascadeType.ALL, mappedBy="class_d", fetch=FetchType.EAGER)
    public List<Class_B> myArray;

    public Class_D() {
        myArray = new ArrayList<Class_B>();
    }
}

Code

// Definition.
Class_B b = new Class_B(); b.myId =  9;
Class_C c = new Class_C(); c.myId = 18;
Class_D d = new Class_D(); d.myId = 92;
d.myArray.add(b);
d.myArray.add(c);

// Saving.
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(d);
session.getTransaction().commit();
session.close();

// Loading.
Session session2 = sessionFactory.openSession();
session2.beginTransaction();
Class_D d2 = (Class_D)session2.createQuery("from " + Class_D.class.getName()).uniqueResult();
session2.getTransaction().commit();
session2.close();

In the debugger I can compare instance d with d2 (they are not the same instance, but have the same myId). d2 has an empty myArray.

No exception - No Oracle error - No nothing

Why?

Notes:

1. Hibernate 3.6.0 Final + Oracle 11g + pure Java

2. Using annotations

3. I've reviewed this and this but still can't get this simple example to work (ffs!)

4. I'll be able to update next on Sunday - please forgive me if I don't reply until then


When saving relationship to the database Hibernate looks at the owning side. For bidirectional one-to-many relationships the owning side is "many", i.e. Class_B in your case.

Therefore database reflects state of Class_B.class_d, and you should set its value when associating Class_B to Class_D (it would be better to create a method to set both sides at once):

public class Class_D {
    ...
    public void addToMyArray(Class_B class_b) {
        myArray.add(class_b);
        class_b.setClass_D(this);
    }
}

d.addToMyArray(b);
d.addToMyArray(c);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号