Hibernate: limit query with one-to-many

前端 未结 5 2116
暗喜
暗喜 2020-12-10 19:48

For example, I have the Service entity:

@OneToMany(fetch = FetchType.EAGER, mappedBy = \"service\")
pu         


        
相关标签:
5条回答
  • 2020-12-10 19:59

    I solved the problem using @Filter:

    @FilterDef(name = "dateFilter", parameters = {
            @ParamDef(name = "date1", type = "date"),
            @ParamDef(name = "date2", type = "date") })
    @Filter(name = "dateFilter", condition = "date >= :date1 and date <= :date2")
    

    and applying it to session:

    session.enableFilter("dateFilter")
                    .setParameter("date1", date1)
                    .setParameter("date2", date2);
    

    BTW, when working with Hibernate, what should I use for queries: it's own mechanism or "raw" SQL like "inner join" in this case?

    0 讨论(0)
  • 2020-12-10 20:05

    You can use Restrictions.le("date2",date2) and Restrictions.gt("date1",date1) while querying. see this link.

    http://www.mkyong.com/hibernate/hibernate-criteria-examples/

    following is also very useful

    http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html

    0 讨论(0)
  • 2020-12-10 20:08

    You can use HQL to create query for this case.

    http://www.mkyong.com/hibernate/hibernate-query-examples-hql/

    0 讨论(0)
  • 2020-12-10 20:10
    Criteria criteria = session.createCriteria(Service.class);
    if(date1!=null){
        criteria.add(Expression.ge("serviceStatuses.date1",date1));
    }
    if(date2!=null){
        criteria.add(Expression.le("serviceStatuses.date2",date2));
    }
    return criteria.list();
    

    got it?

    0 讨论(0)
  • 2020-12-10 20:12

    You can make use of @Where clause:

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "service")
    @Where(clause = "is_deleted = 'N'")
    List<ServiceStatus> serviceStatuses = new ArrayList<ServiceStatus>();
    

    The above implementation allows you to filter records which are is_deleted = N. Similarly you can write your own implementation.

    0 讨论(0)
提交回复
热议问题