• JPA标准WHERE子句


    WHERE子句用于对数据库应用条件并基于该条件获取数据。 在Criteria API中,AbstractQuery接口的where()方法用于设置查询条件。

    标准WHERE示例

    在这里,我们将在student表上执行多个WHERE操作。假设该表包含以下记录 -

    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');
    
    SQL

    现在,请按照以下步骤执行操作: -

    第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;
        }
    
    }
    
    Java

    第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>
    
    XML

    这里,我们创建了基本实体类并将配置映射到persistence.xml 文件中,可以通过以下方式执行不同类型的SELECT排序操作 -

    1. JPQL大于和小于条件

    在这里,我们将通过一个简单的示例演示如何从数据库指定大于和小于条件查询获取符合条件的数据。

    文件:Comparison.java -

    package com.yiibai.jpa.jpql;
    
    import com.yiibai.jpa.StudentEntity;
    import javax.persistence.*;
    import javax.persistence.criteria.*;
    
    import java.util.*;
    
    public class Comparison {
    
        public static void main(String args[]) {
    
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("Student_details");
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
    
            CriteriaBuilder cb = em.getCriteriaBuilder();
    
            AbstractQuery<StudentEntity> cq1 = cb.createQuery(StudentEntity.class);
            AbstractQuery<StudentEntity> cq2 = cb.createQuery(StudentEntity.class);
    
            Root<StudentEntity> stud1 = cq1.from(StudentEntity.class);
    
            cq1.where(cb.greaterThan(stud1.get("s_age"), 22));
    
            CriteriaQuery<StudentEntity> select1 = ((CriteriaQuery<StudentEntity>) cq1).select(stud1);
            TypedQuery<StudentEntity> tq1 = em.createQuery(select1);
            List<StudentEntity> list1 = tq1.getResultList();
    
            System.out.println("Students having age greater than 22");
    
            System.out.print("s_id");
            System.out.print("	 s_name");
            System.out.println("	 s_age");
    
            for (StudentEntity s : list1) {
                System.out.print(s.getS_id());
                System.out.print("	" + s.getS_name());
                System.out.println("	" + s.getS_age());
            }
    
            Root<StudentEntity> stud2 = cq2.from(StudentEntity.class);
    
            cq2.where(cb.lessThan(stud2.get("s_age"), 22));
    
            CriteriaQuery<StudentEntity> select2 = ((CriteriaQuery<StudentEntity>) cq2).select(stud2);
            TypedQuery<StudentEntity> tq2 = em.createQuery(select2);
            List<StudentEntity> list2 = tq2.getResultList();
    
            System.out.println("Students having age Less than 22");
    
            System.out.print("s_id");
            System.out.print("	 s_name");
            System.out.println("	 s_age");
    
            for (StudentEntity s : list2) {
                System.out.print(s.getS_id());
                System.out.print("	" + s.getS_name());
                System.out.println("	" + s.getS_age());
            }
    
            em.getTransaction().commit();
            em.close();
            emf.close();
        }
    }
    
    Java

    执行上面代码,得到以下输出结果 -

    Students having age greater than 22
    s_id     s_name     s_age
    101    Gaurav    24
    104    Ronit    26
    Students having age Less than 22
    s_id     s_name     s_age
    103    Chris    20
    105    Roy    21
    
    Shell

    2. JPQL Between条件

    在这里,我们将通过一个简单的示例演示如何从数据库指定Between条件查询获取符合条件的数据。

    文件:Between.java -

    package com.yiibai.jpa.jpql;
    
    import com.yiibai.jpa.StudentEntity;
    import javax.persistence.*;
    import javax.persistence.criteria.*;
    
    import java.util.*;
    
    public class Between {
    
        public static void main(String args[]) {
    
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("Student_details");
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
    
            CriteriaBuilder cb = em.getCriteriaBuilder();
    
            AbstractQuery<StudentEntity> cq = cb.createQuery(StudentEntity.class);
    
            Root<StudentEntity> stud = cq.from(StudentEntity.class);
    
            cq.where(cb.between(stud.get("s_age"), 22, 26));
            CriteriaQuery<StudentEntity> select = ((CriteriaQuery<StudentEntity>) cq).select(stud);
            TypedQuery<StudentEntity> tq = em.createQuery(select);
            List<StudentEntity> list = tq.getResultList();
    
            System.out.println("Students having age between 22 and 26");
    
            System.out.print("s_id");
            System.out.print("	 s_name");
            System.out.println("	 s_age");
    
            for (StudentEntity s : list) {
                System.out.print(s.getS_id());
                System.out.print("	" + s.getS_name());
                System.out.println("	" + s.getS_age());
            }
    
            em.getTransaction().commit();
            em.close();
            emf.close();
        }
    }
    
    Java

    执行上面代码,得到以下输出结果 -

    Students having age between 22 and 26
    s_id     s_name     s_age
    101    Gaurav    24
    102    Rahul    22
    104    Ronit    26
    
    Shell

    3. JPQL Like条件

    在这里,我们将通过一个简单的示例演示如何从数据库指定Like条件查询获取符合条件的数据。

    文件:Like.java -

    package com.yiibai.jpa.jpql;
    
    import com.yiibai.jpa.StudentEntity;
    import javax.persistence.*;
    import javax.persistence.criteria.*;
    
    import java.util.*;
    
    public class Like {
    
        public static void main(String args[]) {
    
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("Student_details");
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
    
            CriteriaBuilder cb = em.getCriteriaBuilder();
    
            AbstractQuery<StudentEntity> cq = cb.createQuery(StudentEntity.class);
    
            Root<StudentEntity> stud = cq.from(StudentEntity.class);
    
            cq.where(cb.like(stud.get("s_name"), "R%"));
            CriteriaQuery<StudentEntity> select = ((CriteriaQuery<StudentEntity>) cq).select(stud);
            TypedQuery<StudentEntity> tq = em.createQuery(select);
            List<StudentEntity> list = tq.getResultList();
    
            System.out.println("Students name starting with R");
    
            System.out.print("s_id");
            System.out.print("	 s_name");
            System.out.println("	 s_age");
    
            for (StudentEntity s : list) {
                System.out.print(s.getS_id());
                System.out.print("	" + s.getS_name());
                System.out.println("	" + s.getS_age());
            }
            em.getTransaction().commit();
            em.close();
            emf.close();
        }
    }
    
    Java

    执行上面示例代码,得到以下结果 -

    Students name starting with R
    s_id     s_name     s_age
    102    Rahul    22
    104    Ronit    26
    105    Roy    21
    
    Shell

    4. JPQL In条件

    在这里,我们将通过一个简单的示例演示如何从数据库指定In条件查询获取符合条件的数据。

    文件:Like.java -

    package com.yiibai.jpa.jpql;
    
    import com.yiibai.jpa.StudentEntity;
    import javax.persistence.*;
    import javax.persistence.criteria.*;
    
    import java.util.*;
    
    public class In {
    
        public static void main(String args[]) {
    
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("Student_details");
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
    
            CriteriaBuilder cb = em.getCriteriaBuilder();
    
            AbstractQuery<StudentEntity> cq = cb.createQuery(StudentEntity.class);
    
            Root<StudentEntity> stud = cq.from(StudentEntity.class);
    
            cq.where(cb.in(stud.get("s_age")).value(22).value(24));
            CriteriaQuery<StudentEntity> select = ((CriteriaQuery<StudentEntity>) cq).select(stud);
            TypedQuery<StudentEntity> tq = em.createQuery(select);
            List<StudentEntity> list = tq.getResultList();
    
            System.out.println("Students having age 22 and 24");
    
            System.out.print("s_id");
            System.out.print("	 s_name");
            System.out.println("	 s_age");
    
            for (StudentEntity s : list) {
                System.out.print(s.getS_id());
                System.out.print("	" + s.getS_name());
                System.out.println("	" + s.getS_age());
            }
    
            em.getTransaction().commit();
            em.close();
            emf.close();
        }
    }
    
    Java

    执行上面示例代码,得到以下结果 -

    Students having age 22 and 24
    s_id     s_name     s_age
    101    Gaurav    24
    102    Rahul    22
  • 相关阅读:
    注册接口
    配置node 的路由
    mongoose 与 mylab 的使用 (1)
    PHP中PDO错误/异常(PDOException)处理
    如何使用PDO查询Mysql来避免SQL注入风险?ThinkPHP 3.1中的SQL注入漏洞分析!
    PHP5中PDO的入门教程
    PHP文件夹文件拷贝/复制函数 dir_copy($src = '', $dst = '')
    php将图片以二进制保存到mysql数据库并显示
    php 显示sqlserver二进制图片
    XML文档的PHP程序查询代码
  • 原文地址:https://www.cnblogs.com/borter/p/12424008.html
Copyright © 2020-2023  润新知