java - select all the subchilds details in jpa self refence for dynamic hierarchy -
i using play 2.3.x java jpa mysql , got stuck in database problem.i have entity executive
self refrencing relation of one-to-many
(i using because want create dynamic hierarchical database).
executive.java model
@entity public class executive { @id @column(name = "id", nullable = false) @generatedvalue(strategy = generationtype.auto) private long id; @constraints.required private string full_name; @manytoone private executive upperexecutive; @onetomany(mappedby="upperexecutive") private collection<executive> lowerexecutives; private string type; }
so given id of executive want find subuser of did simple select like
public static executive gethierachyuser(long id) { executive executive = (executive)jpa.em().createquery("select e executive e e.id=:id").setparameter("id",id).getsingleresult(); return executive; }
but in view dont know how long hierarchy dont know how executive of below executive.so if hierarchy is
in view passing found executive object , doing getlowerexecutive()
how know have continue after user4 , stop doing after user6.what doing now
<ol> @for(executive <- executivelist) { <li>@executive.getfull_name @if(executive.getlowerexecutives.size()>0){ <ol> @for(executive2 <- executive.getlowerexecutives) { <li>@executive2.getfull_name</li> } </ol> } </li><br><br> } </ol>
and how work in other table have executiverecord entity one-to-many relation executive.how can user view lower executive history?
and if there other way in user can view executive below it?
thanks in advance.
thanks
if want display whole hierarchy can go recursively through until there no children left fetched.
make sure initialize collections:
@onetomany(mappedby="upperexecutive") private collection<executive> lowerexecutives = new arraylist<>();
after fetched root executive, can go recursivily through whole hierarchy:
public void fetchchildren(executive executive) { if(!executive.lowerexecutives.isempty()) { for(executive lowerexecutive : executive.lowerexecutives) { fetchchildren(lowerexecutive); } } }
this way hierarchy initialized when have display in ui, you'd have use same recursion algorithm displaying children.
Comments
Post a Comment