Sleep mode.

I have a parent / child relationship in the same table, let's say as simple as

id | parent_id | some_data 

I am trying to understand / implement best practices on how to build Hibernate classes for relationships with a single table.

I have a feed that appears from somewhere, and it has a nested JSON structure, so after parsing I want to have this view in OracleDB.

Feed looks like

 { 1: => 2: => 3 => 4: => 5 => 6 } 

this data should be in db as:

 1 | 0 (main rec, no parent) 2 | 1 3 | 2 4 | 2 5 | 4 6 | 1 

And it can be deeper and deeper ...

I would like to traverse the JSON structure and build the classes that I end up storing in db

 session.save(parent) 

parent will be an instance of my mapped sleep class, name it Feed.

Each time I go down with a tree, it creates a new feed, finds it as a parent and adds it to the list.

 Feed **parent** = new Feed(); -> Feed child2 = new Feed(); child2.setParent(parent) parent.add(child2); -> Feed child3 = new Feed(); child3.setParent(child2) child2.add(child3); Feed child4 = new Feed(); child4.setParent(child2) child2.add(child4); ............. session.save(**parent**) 

My question is: can I use the @ManyToOne and @OneToMany approach?

I also looked at @Inheritance (strategy = InheritanceType.SINGLE_TABLE), but I don’t think I can apply it to my problem, since I don’t know the parents, they are dynamic. I could not create a parent class and extend it.

So, on the bottom line, I'm trying to solve two problems.

  • Easy parental retention

  • How to get data from parent to sheet when I need it

An example of using some classes with hibernate matching.

+5
source share
2 answers

It seems that all I need to do is:

 @Entity @Table(name = "table_name") public class TableName{ ...... @Transient private Long parentId; ...... @ManyToOne(fetch = FetchType.LAZY, optional=true) @JoinColumn(name="parent_id") private TableName parent; @OneToMany(mappedBy="parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval=true) private Set<TableName> children = new HashSet<TableName>(); 

Than just

 TableName papa = new TableName(); papa.setParent(null); // parent TableName kid1 = new TableName(); kid1.setParent(papa); papa.getChildren().add(kid1); TableName kid1_1 = new TableName(); kid1_1.setParent(kid1); kid1.getChildren().add(kid1_1); TableName kid2 = new TableName(); kid2.setParent(papa); papa.getChildren().add(kid2); session.save(papa) 
+7
source

Why don't you create a binding to one of many relationships, while maintaining cascade = all. Therefore, individual child objects do not need to be stored separately. It is enough to save only the parent. For instance.

Adding a One-to-Many Relationship to the Source Parent / Child Link

0
source

All Articles