Cyclic relationships in Hibernate -
i want map tree in hibernate, persisting results in exception because of cyclic reference (the relationships not bidirectional).
class node { @manytoone node parent; @onetoone node leftchild; @onetoone node rightchild; }
node n references left child l in turn references n again parent. also, node n references right child r in turn again references n again parent. however, cannot make relationships bidirectional, because parent inverse of both leftchild , rightchild. best way make model persistable?
regards, jochen
i don't see problem:
@entity class node { @id @generatedvalue private int id; private string name; @manytoone(cascade = cascadetype.all) node parent; @onetoone(cascade = cascadetype.all) node leftchild; @onetoone(cascade = cascadetype.all) node rightchild; node() {} public node(string name) { this.name = name; } // omitted getters , setters brevity } public static void main(string[] args) { sessionfactory sessionfactory = new configuration() .addannotatedclass(node.class) .setproperty("hibernate.connection.url", "jdbc:h2:mem:foo;db_close_delay=-1") .setproperty("hibernate.hbm2ddl.auto", "create") .buildsessionfactory(); session session = sessionfactory.opensession(); transaction transaction = session.begintransaction(); node = new node("a"); node b = new node("b"); node c = new node("c"); node d = new node("d"); node e = new node("e"); a.setleftchild(b); b.setparent(a); a.setrightchild(c); c.setparent(a); b.setleftchild(d); d.setparent(b); b.setrightchild(e); e.setparent(b); system.out.println("before saving:"); print(a, 1); serializable rootnodeid = session.save(a); transaction.commit(); session.close(); session = sessionfactory.opensession(); node root = (node) session.load(node.class, rootnodeid); system.out.println("freshly loaded:"); print(root, 1); session.close(); } private static void print(node node, int depth) { if (node == null) { return; } system.out.format("%" + depth + "s\n", node); print(node.getleftchild(), depth + 1); print(node.getrightchild(), depth + 1); }
Comments
Post a Comment