java - Hibernate. Keep reference to last child -


i have simple parent-child relationship @onetomany , @manytoone annotations.

@entity public class parent {         @onetomany(cascade = cascadetype.all, mappedby = "parent", fetch = fetchtype.lazy)        private list<child> children = new arraylist<>();  }  public class child {       @manytoone( fetch = fetchtype.lazy, optional = false)       @joincolumn( name = "parent_id" )       @foreignkey( name = "fk_child_parent" )       private parent parent;  } 

but want keep reference current(last) child inside parent entity.

how in right way? should introduce new undirectional @onetoonerelationship in parent? this:

   @onetoone( optional = true, cascade = cascadetype.all, fetch = fetchtype.eager)    @joincolumn( name = "current_child_id", nullable = false )    @foreignkey( name = "fk_parent_child" )    private child currentchild; 

so gonna have issue of determining insertion order of child elements existing parent's , children on application start. should therefore have data preserved in persistence layer.

add created (or updated) timestamp child class, can determine how want handle initialization of field (i.e. column defaults or triggers etc.). required information should available in code, add 'compareto' method child (to sort) , add following getmostrecentchild method parent class.

@entity public class parent {     @onetomany(cascade = cascadetype.all, mappedby = "parent", fetch = fetchtype.lazy)     public list<child> children = new arraylist<>();      public child getmostrecentchild() {         if(children == null || children.isempty()) {             return null;         }         return collections.sort(children).get(0);     } }  public class child {     @manytoone( fetch = fetchtype.lazy, optional = false)     @joincolumn( name = "parent_id" )     @foreignkey( name = "fk_child_parent" )     public parent parent;      @column( name = "created_ts" )     public createdts;      public int compareto(child other) {         return created_ts.compareto(other);     }  } 

the implementation details how find currentchild irrelevant. use treeset or loop find currentchild.

edit: argument why better currentchild column.

if don't above answer consider following

  1. adding currentchild field provides 2 references same object. therefore not normalized, whereas, adding timestamp adds normalized column schema information require (and more) can derived in way directly coupled logic attempting encapsulate in currentchild column.
  2. in order ensure currentchild doesn't mismatch it's intended value, must encapsulate it's logic in either hibernate object, can override on database level, or triggers on database level, can ugly , hard trace (whereas default value , 'on update' created_ts field common place)

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -