How to filter the child entity while quering the parent in hibernate

我是研究僧i 提交于 2019-12-08 01:54:44

问题


Lets say that i have two entities

public class EntityA
{
   @id
   @GeneratedValue
   @Column(name="id")
   private Long id;

   @OneToMany(mappedBy="EntityA")
   @JoinColumn(name = "entityA_id")
   private List<EntityB> entityBList;


} 

public class EntityB
{
  @Column(name = "MODEL_PERCENT")
  private BigDecimal modelPercent;

  @ManyToOne
  @joincolumn(name="entityA_id") 
  private EntityA entityA;

}

What i want now is, when i fetch the EntityA i want to add a where clause to fetch all EntityBs' whose modelPercent is greater than 0.

I do not want to use filters since this requirement is only for this perticular situation.

Eg Data:

 EntitytA table
 id 
  1
EntityB table
 id   EntitytA_Id  modelPercent
  1      1           10
  2      1           0

I need a way, may be an hql to fetch the EntityA so that when i say EntityA.getEntityBList() it should return only 1 record(one whose model percent is 10(greater that zero)).

I tried below query but it doesnt seem to work. i.e it returns both the records from entityB

select a from EntityA a,IN( a.EntityBList) b where a.id =:id and b.modelPercent>0   

Any suggestion or pointers to some examples would be of great help.

Thanks


回答1:


1) You have errors in mapping
EntityA - has property and field access at the same time
EntityB - hasn't ID and has property and field access at the same time
2) HQL query is

SELECT eA FROM EntityA LEFT JOIN eA.entityBList eB WHERE eA.id =:id AND eB.modelPercent > 0


来源:https://stackoverflow.com/questions/12190794/how-to-filter-the-child-entity-while-quering-the-parent-in-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!