hibernate之條件查詢

來源:互聯網
上載者:User

標籤:查詢方式   通過   tran   指定   create   工具類   stc   彙總   串連方式   

一、條件查詢簡介

條件查詢是更據物件導向特色的資料查詢方式,主要通過如下3個類完成

1、Criteria:代表一次查詢

2、Criterion:代表一個查詢條件

3、Restrictions:產生查詢條件的工具類

執行條件查詢的步驟

1、擷取Hibernate session對象

2、調用session的createCriteria()方法建立Criteria查詢對象

3、使用Restrictions的靜態方法建立Criterion查詢條件

4、通過Criteria的add()方法添加查詢條件到Criteria查詢中

5、執行Criteria的list()或uniqueResult()方法返回結果集

二、條件查詢

1、整表查詢

        Criteria c = session.createCriteria(CriteriaTeacher.class);            List<CriteriaTeacher> list = c.list();            for (CriteriaTeacher t : list) System.out.println(t.getName());

2、加入查詢條件(通過Criteria的add()方法和Restrictions的靜態方法添加)

Criteria c = session.createCriteria(CriteriaTeacher.class).add(Restrictions.like("name", "%1%"));            List<CriteriaTeacher> list = c.list();            for (CriteriaTeacher t : list) System.out.println(t.getName());

3、關聯查詢(前提持久化類內部有映射關係)

 如果需要使用關聯實體的屬性來增加查詢條件,則需再次使用createCriteria()方法

a、預設連結方式

        Criteria c = session                    .createCriteria(CriteriaStudent.class)                    .add(Restrictions.like("name", "%1%"))                    .createCriteria("criteriaTeacher")
            //.createCriteria("criteriaTeacher", "ct")//為關聯實體指定別名 .add(Restrictions.like("name", "%1%")); List<CriteriaStudent> list = c.list(); for (CriteriaStudent s : list) System.out.println("studentName = " + s.getName() + " | teacherName = " + s.getCriteriaTeacher().getName());

b、指定連結方式

        Criteria c = session                    .createCriteria(CriteriaStudent.class)                    .add(Restrictions.like("name", "%1%"))                    .createCriteria("criteriaTeacher", JoinType.LEFT_OUTER_JOIN);//左串連方式            List<CriteriaStudent> list = c.list();            for (CriteriaStudent s : list)                System.out.println("studentName = " + s.getName() + " | teacherName = " + s.getCriteriaTeacher().getName());

 c、也可以使用createAlias()方法代替createCriteria()方法

        Criteria c = session                    .createCriteria(CriteriaStudent.class)                    .add(Restrictions.like("name", "%1%"))                    .createAlias("criteriaTeacher", "ct")                    .add(Restrictions.like("ct.name", "%1%"));            List<CriteriaStudent> list = c.list();            for (CriteriaStudent s : list)                System.out.println("studentName = " + s.getName() + " | teacherName = " + s.getCriteriaTeacher().getName());

4、投影、彙總、分組查詢

hibernate中使用Projection介面代表投影運算,hibernate通過Criteria的setProjection(Projections p)方法進行投影運算,其中Projections作為產生Projection的工廠。

a、投影運算查詢

        Criteria c = session                    .createCriteria(CriteriaStudent.class)                    .setProjection(Projections.projectionList()                    .add(Projections.rowCount()));//統計表中記錄條數            System.out.println(c.uniqueResult());
        Criteria c = session                    .createCriteria(CriteriaStudent.class)                    .setProjection(Projections.projectionList()                    .add(Projections.count("name"))                    .add(Projections.groupProperty("name")));//據name值分組統計            List list = c.list();            for(Object ob : list) {                Object[] ob1 = (Object[]) ob;                System.out.println(ob1[1] + " | " + ob1[0]);            }
        Criteria c = session                    .createCriteria(CriteriaStudent.class)                    .setProjection(Projections.projectionList()                    .add(Projections.groupProperty("name")));//name去重後列表            List<String> list = c.list();            for(String s : list) {                System.out.println(s);            }

用alias()方法為指定投影指定別名

        Criteria c = session                    .createCriteria(CriteriaStudent.class)                    .setProjection(Projections.projectionList()                    .add(Projections.alias(Projections.count("name"), "count"))//指定別名                    .add(Projections.groupProperty("name")))                    .addOrder(Order.desc("count"));//用別名排序            List list = c.list();            for(Object ob : list) {                Object[] ob1 = (Object[]) ob;                System.out.println(ob1[1] + " | " + ob1[0]);            }

 b、選取查詢(指定要尋找的列)

查詢一列

        Criteria c = session                    .createCriteria(CriteriaStudent.class)                    .setProjection(Projections.projectionList()                    .add(Property.forName("name")));            List<String> list = c.list();            for(String s : list) {                System.out.println(s);            }

查詢多列

         Criteria c = session                    .createCriteria(CriteriaStudent.class)                    .createAlias("criteriaTeacher", "ct")                    .setProjection(Projections.projectionList()                    .add(Property.forName("ct.name"))                    .add(Property.forName("name")));            List list = c.list();            for(Object ob : list) {                Object[] ob1 = (Object[]) ob;                System.out.println(ob1[1] + " | " + ob1[0]);            }

5、離線查詢和子查詢

DetachedCriteria代表離線查詢(允許再session範圍之外建立一個查詢)和子查詢(把DetachedCriteria的查詢結果傳入Criteria中作為查詢條件時,DetachedCriteria就變成了子查詢)

        DetachedCriteria sub = DetachedCriteria                    .forClass(CriteriaTeacher.class)                    .setProjection(Projections.projectionList()                    .add(Property.forName("id")))                    .add(Restrictions.like("name", "%1%"));            Criteria c = session                    .createCriteria(CriteriaStudent.class)                    .add(Subqueries.propertyIn("criteriaTeacher", sub));            List<CriteriaStudent> list = c.list();            for(CriteriaStudent s : list) {                System.out.println(s.getName() + " | " + s.getCriteriaTeacher().getName());            }

 

下面是測試學習時用到的持久化類

@Entity@Table(name = "criteria_teacher")public class CriteriaTeacher {    @Id    @GeneratedValue    private Long id;    private String name;    @OneToMany(targetEntity = CriteriaStudent.class, mappedBy = "criteriaTeacher")    private Set<CriteriaStudent> criteriaStudents = new HashSet<CriteriaStudent>();    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Set<CriteriaStudent> getCriteriaStudents() {        return criteriaStudents;    }    public void setCriteriaStudents(Set<CriteriaStudent> criteriaStudents) {        this.criteriaStudents = criteriaStudents;    }}
@Entity@Table(name = "criteria_student")public class CriteriaStudent {    @Id    @GeneratedValue    private Long id;    private String name;    @ManyToOne(targetEntity = CriteriaTeacher.class)    @JoinColumn(name = "teacher_id", referencedColumnName = "id", nullable = false)    private CriteriaTeacher criteriaTeacher;    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public CriteriaTeacher getCriteriaTeacher() {        return criteriaTeacher;    }    public void setCriteriaTeacher(CriteriaTeacher criteriaTeacher) {        this.criteriaTeacher = criteriaTeacher;    }}

測試類別

public class CriteriaTestController {    public static void main(String[] args) {        Configuration cf = new Configuration().configure();        SessionFactory sf = cf.buildSessionFactory();        Session session = sf.openSession();        Transaction ts = session.beginTransaction();        try {            Criteria c = session                    .createCriteria(CriteriaStudent.class)                    .setProjection(Projections.projectionList()                    .add(Property.forName("name")));            List<String> list = c.list();            for(String s : list) {                System.out.println(s);            }            ts.commit();        } finally {            session.close();            sf.close();        }    }}

 

hibernate之條件查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.