How to filter an entity in hibernate with hibernate filters

风格不统一 提交于 2020-01-24 23:03:15

问题


I need to filter an entity in a list of objects, for example:

public class Student {

    private int id;

    private List<Course> courses;

}

public class Course {

    private int id;

    private String name;

    private float note;

    private Classroom classroom;

}

public class Classroom {

    private int id;

    private String classroom;

} 

How to obtain a student object with a list of courses with only notes greater than 70, and located in classroom 23 (for example)?

Is there a way to use the name of the entity instead of the one of the column of the database?

Or how do I associate with sql the alias generated by hibernate for the entity?

I attach a link from the hibernate filters: https://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html/ch19.html


回答1:


Ok it think this should do the trick:

Entities

public class Student {

    private int id;

    @OneToMany(mappedBy = "student")
    @Filter(name = "defaultCoursesFilter")   
    private List<Course> courses;

}

@FilterDef(name = "defaultCoursesFilter"
                , defaultCondition=" notes > 70")
public class Course {

    private int id;

    private String name;

    private float note;

    @ManyToOne
    @Filter(name = "defaultClassromFilter")
    private Classroom classroom;

}


@FilterDef(name = "defaultClassromFilter"
                , defaultCondition=" id  = 23")
public class Classroom {

    private int id;

    private String classroom;

} 

Before query

Session session = sessionFactory.getCurrentSession();
session.enableFilter("defaultCoursesFilter");
session.enableFilter("defaultClassromFilter");

// query


来源:https://stackoverflow.com/questions/41821516/how-to-filter-an-entity-in-hibernate-with-hibernate-filters

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