java - Using criteriabuilder to build type safe select with treat -


i have base abstract class table, abstract class not keep columns

@entity @table(name = "mytable") public abstract class mytable {     //... } 

normally required column data derived classes using treat in criteriabuilder

@entity public class myclassa extends mytable {     //... } @entity public class myclassb extends mytable {     //... }  root<mytable> mytable = cq.from(mytable.class); cq.where(cb.or(     cb.equal(cb.treat(mytable, myclassa.class).get(myclassa_.infoa), "a"),     cb.equal(cb.treat(mytable, myclassb.class).get(myclassb_.infob), "b") )) 

here both infoa , infob same column in mytable in database.

my question how write type-safe select select both infoa , infob in single select?

i'm not sure, if there real reason not move both infoa , infob variables base class, oo principles suggest, since simplifies then.

but if made unintentionally, suggest making small refactorings , use inheritance mapping benefits provided orm frameworks:

@entity public abstract class mytable {      @javax.persistence.id     @generatedvalue(strategy = generationtype.identity)     private long id;      private string info;      public string getinfo() {         return info;     }      public void setinfo(string info) {         this.info = info;     }      public long getid() {        return id;     }      public void setid(long id) {        id = id;     } }  @entity public class myclassa extends mytable {     //... } @entity public class myclassb extends mytable {     //... } 

so able query myclassa , myclassb entites polymorphicly:

criteriabuilder builder = entitymanager.getcriteriabuilder();         criteriaquery<mytable> query = builder.createquery( mytable.class );         root<mytable> root = query.from( mytable.class );         query.select( root );         list<mytable> entities = entitymanager.createquery( query ).getresultlist(); 

in case of hibernate, check out following:

http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/hibernate_user_guide.html#entity-inheritance


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -