JPA標準ORDER BY子句

ORDER BY子句用於對數據進行排序並按升序或降序排列數據。 CriteriaQuery接口提供了orderBy()方法來定義排序的類型。

標準ORDER BY示例

在這裏,我們將在student表上執行多個ORDER BY操作。假設該表格包含以下記錄 -

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `S_ID` int(11) NOT NULL,
  `S_NAME` varchar(255) DEFAULT NULL,
  `S_AGE` int(11) DEFAULT NULL,
  PRIMARY KEY (`S_ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('101', 'Gaurav', '24');
INSERT INTO `student` VALUES ('102', 'Rahul', '22');
INSERT INTO `student` VALUES ('103', 'Chris', '20');
INSERT INTO `student` VALUES ('104', 'Ronit', '26');
INSERT INTO `student` VALUES ('105', 'Roy', '21');

現在,請按照以下步驟執行操作: -

第1步: 創建一個實體類。在com.yiibai.jpa包下創建了StudentEntity.java類文件。 該類包含三個屬性:s_ids_names_age以及所有必需的註解。

文件:StudentEntity.java -

package com.yiibai.jpa;

import javax.persistence.*;

@Entity
@Table(name = "student")
public class StudentEntity {

    @Id
    private int s_id;
    private String s_name;
    private int s_age;

    public StudentEntity(int s_id, String s_name, int s_age) {
        super();
        this.s_id = s_id;
        this.s_name = s_name;
        this.s_age = s_age;
    }

    public StudentEntity() {
        super();
    }

    public int getS_id() {
        return s_id;
    }

    public void setS_id(int s_id) {
        this.s_id = s_id;
    }

    public String getS_name() {
        return s_name;
    }

    public void setS_name(String s_name) {
        this.s_name = s_name;
    }

    public int getS_age() {
        return s_age;
    }

    public void setS_age(int s_age) {
        this.s_age = s_age;
    }

}

第2步: 將實體類和其他數據庫配置映射到 persistence.xml 文件中。

文件:Persistence.xml -

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
    xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="Student_details">
        <class>com.yiibai.jpa.StudentEntity</class>  
        <properties>
            <property name="javax.persistence.jdbc.driver"
                value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url"
                value="jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password"
                value="123456" />
            <property name="eclipselink.logging.level" value="SEVERE" />
            <property name="eclipselink.ddl-generation"
                value="create-or-extend-tables" />
        </properties>
    </persistence-unit>

</persistence>

這裏,我們創建了基本實體類並將配置映射到persistence.xml 文件中,可以通過以下方式執行不同類型的SELECT排序操作 -

1. 按升序排序

在這裏,我們將通過一個簡單的示例從數據庫查詢並按s_age字段升序排序。

文件:Asc.java -

package com.yiibai.jpa.jpql;

import com.yiibai.jpa.StudentEntity;
import javax.persistence.*;
import javax.persistence.criteria.*;

import java.util.*;

public class Asc {

    public static void main(String args[]) {

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("Student_details");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<StudentEntity> cq = cb.createQuery(StudentEntity.class);

        Root<StudentEntity> stud = cq.from(StudentEntity.class);

        cq.orderBy(cb.asc(stud.get("s_age")));
        CriteriaQuery<StudentEntity> select = cq.select(stud);
        TypedQuery<StudentEntity> q = em.createQuery(select);
        List<StudentEntity> list = q.getResultList();

        System.out.print("s_id");
        System.out.print("\t s_name");
        System.out.println("\t s_age");

        for (StudentEntity s : list) {
            System.out.print(s.getS_id());
            System.out.print("\t" + s.getS_name());
            System.out.println("\t" + s.getS_age());
        }

        em.getTransaction().commit();
        em.close();
        emf.close();
    }
}

執行上面代碼,得到以下輸出結果 -

s_id     s_name     s_age
103    Chris    20
105    Roy    21
102    Rahul    22
101    Gaurav    24
104    Ronit    26

2. 按降序排序

在這裏,我們將通過一個簡單的示例從數據庫查詢並按s_age字段降序排序。

文件:Desc.java -

package com.yiibai.jpa.jpql;

import com.yiibai.jpa.StudentEntity;
import javax.persistence.*;
import javax.persistence.criteria.*;

import java.util.*;

public class Desc {

    public static void main(String args[]) {

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("Student_details");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<StudentEntity> cq = cb.createQuery(StudentEntity.class);

        Root<StudentEntity> stud = cq.from(StudentEntity.class);

        cq.orderBy(cb.desc(stud.get("s_age")));
        CriteriaQuery<StudentEntity> select = cq.select(stud);
        TypedQuery<StudentEntity> q = em.createQuery(select);
        List<StudentEntity> list = q.getResultList();

        System.out.print("s_id");
        System.out.print("\t s_name");
        System.out.println("\t s_age");

        for (StudentEntity s : list) {
            System.out.print(s.getS_id());
            System.out.print("\t" + s.getS_name());
            System.out.println("\t" + s.getS_age());
        }

        em.getTransaction().commit();
        em.close();
        emf.close();
    }
}

執行上面代碼,得到以下輸出結果 -

s_id     s_name     s_age
104    Ronit    26
101    Gaurav    24
102    Rahul    22
105    Roy    21
103    Chris    20
0 條評論,你可以發表評論,我們會進行改進
Comment author placeholder