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:
Comments
Post a Comment