首页 > 其他分享 >第二百七十一节 JPA教程 - JPA查询like Escape示例

第二百七十一节 JPA教程 - JPA查询like Escape示例

时间:2024-10-08 10:48:28浏览次数:9  
标签:二百七十 return String 示例 JPA void Column import public

JPA教程 - JPA查询like Escape示例

如果模式字符串包含应匹配的下划线或百分号,则ESCAPE子句可以使用\指定转义字符:

SELECT d
FROM Department d
WHERE d.name LIKE 'QA\_%' ESCAPE '\'
	

例子

下面的代码来自PersonDaoImpl.java。

package cn.w3cschool.common;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

@Transactional
public class PersonDaoImpl {
  public void test() {
    prepareData();
    
    List l = em.createQuery(
        "SELECT d FROM Department d WHERE d.name LIKE "Q\\_%" ESCAPE "\\"")
        .getResultList();
    for (Object p : l) {
      printResult(p);
    }
  }

  private void prepareData() {
    Address address = new Address();
    address.setState("BC");
    
    Professor p = new Professor();
    p.setId(0);
    p.setName("TOM");
    p.setSalary(1111L);
    p.setAddress(address);

    Department d = new Department();
    d.setId(1);
    d.setName("Design");

    p.setDepartment(d);
    d.getProfessors().add(p);

    Phone phone = new Phone();
    phone.setId(1);
    phone.setNumber("111-111-1111");
    phone.setProfessor(p);
    
    em.persist(p);
    em.persist(phone);
    em.persist(address);
    em.persist(d);
  }

  private static void printResult(Object result) {
    if (result == null) {
      System.out.print("NULL");
    } else if (result instanceof Object[]) {
      Object[] row = (Object[]) result;
      System.out.print("[");
      for (int i = 0; i < row.length; i++) {
        printResult(row[i]);
      }
      System.out.print("]");
    } else if (result instanceof Long || result instanceof Double
        || result instanceof String) {
      System.out.print(result.getClass().getName() + ": " + result);
    } else {
      System.out.print(result);
    }
    System.out.println();
  }

  @PersistenceContext
  private EntityManager em;
}

以下代码来自Professor.java。

package cn.w3cschool.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class Professor {
    @Id
    private int id;
    private String name;
    private long salary;
    @Temporal(TemporalType.DATE)
    private Date startDate;
    
    @OneToOne
    private Address address;
    
    @OneToMany(mappedBy="employee")
    private Collection<Phone> phones = new ArrayList<Phone>();
    
    @ManyToOne
    private Department department;
    
    @ManyToOne
    private Professor manager;
    
    @OneToMany(mappedBy="manager")
    private Collection<Professor> directs = new ArrayList<Professor>();
    
    @ManyToMany(mappedBy="employees")
    private Collection<Project> projects = new ArrayList<Project>();

    public int getId() {
        return id;
    }
    
    public void setId(int empNo) {
        this.id = empNo;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }

    public long getSalary() {
        return salary;
    }

    public void setSalary(long salary) {
        this.salary = salary;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }
    
    public Collection<Phone> getPhones() {
        return phones;
    }
    
    public void addPhone(Phone phone) {
        if (!getPhones().contains(phone)) {
            getPhones().add(phone);
            if (phone.getProfessor() != null) {
                phone.getProfessor().getPhones().remove(phone);
            }
            phone.setProfessor(this);
        }
    }
    
    public Department getDepartment() {
        return department;
    }
    
    public void setDepartment(Department department) {
        if (this.department != null) {
            this.department.getProfessors().remove(this);
        }
        this.department = department;
        this.department.getProfessors().add(this);
    }
    
    public Collection<Professor> getDirects() {
        return directs;
    }
    
    public void addDirect(Professor employee) {
        if (!getDirects().contains(employee)) {
            getDirects().add(employee);
            if (employee.getManager() != null) {
                employee.getManager().getDirects().remove(employee);
            }
            employee.setManager(this);
        }
    }
    
    public Professor getManager() {
        return manager;
    }
    
    public void setManager(Professor manager) {
        this.manager = manager;
    }

    public Collection<Project> getProjects() {
        return projects;
    }
    
    public void addProject(Project project) {
        if (!getProjects().contains(project)) {
            getProjects().add(project);
        }
        if (!project.getProfessors().contains(this)) {
            project.getProfessors().add(this);
        }
    }
    
    public Address getAddress() {
        return address;
    }
    
    public void setAddress(Address address) {
        this.address = address; 
    }
    
    public String toString() {
        return "Professor " + getId() + 
               ": name: " + getName() +
               ", salary: " + getSalary() +
               ", phones: " + getPhones() +
               ", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
               ", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
    }

}

以下代码来自Phone.java。

package cn.w3cschool.common;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class Phone {
    @Id
    private long id;
    private String number;
    private String type;
    @ManyToOne
    Professor employee;
    
    public long getId() {
        return id;
    }
    
    public void setId(long id) {
        this.id = id;
    }
    
    public String getNumber() {
        return number;
    }
    
    public void setNumber(String phoneNo) {
        this.number = phoneNo;
    }
    
    public String getType() {
        return type;
    }
    
    public void setType(String phoneType) {
        this.type = phoneType;
    }
    
    public Professor getProfessor() {
        return employee;
    }

    public void setProfessor(Professor employee) {
        this.employee = employee;
    }

    public String toString() {
        return "Phone id: " + getId() + 
               ", no: " + getNumber() +
               ", type: " + getType();
    }
}

以下代码来自Project.java。

package cn.w3cschool.common;

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.ManyToMany;

@Entity
@Inheritance
public class Project {
    @Id
    protected int id;
    protected String name;
    @ManyToMany
    protected Collection<Professor> employees = new ArrayList<Professor>();
    
    public int getId() {
        return id;
    }
    
    public void setId(int projectNo) {
        this.id = projectNo;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String projectName) {
        this.name = projectName;
    }
    
    public Collection<Professor> getProfessors() {
        return employees;
    }
    
    public void addProfessor(Professor employee) {
        if (!getProfessors().contains(employee)) {
            getProfessors().add(employee);
        }
        if (!employee.getProjects().contains(this)) {
            employee.getProjects().add(this);
        }
    }
    
    public String toString() {
        return getClass().getName().substring(getClass().getName().lastIndexOf(".")+1) + 
                " no: " + getId() + 
                ", name: " + getName();
    }
}

下面的代码来自Department.java。

package cn.w3cschool.common;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Department {
    @Id
    private int id;
    private String name;
    @OneToMany(mappedBy="department")
    private Set<Professor> employees = new HashSet<Professor>();

    public int getId() {
        return id;
    }
    
    public void setId(int deptNo) {
        this.id = deptNo;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String deptName) {
        this.name = deptName;
    }
    
    public Set<Professor> getProfessors() {
        return employees;
    }

    public String toString() {
        return "Department no: " + getId() + 
               ", name: " + getName();
    }
}

以下代码来自Address.java。

package cn.w3cschool.common;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Address {
    @Id
    private int id;
    private String street;
    private String city;
    private String state;
    private String zip;
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getStreet() {
        return street;
    }
    
    public void setStreet(String address) {
        this.street = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }
    public String toString() {
        return "Address id: " + getId() + 
               ", street: " + getStreet() +
               ", city: " + getCity() +
               ", state: " + getState() +
               ", zip: " + getZip();
    }

}

以下是数据库转储。

Table Name: ADDRESS
 Row:
    Column Name: ID,
    Column Type: INTEGER:
    Column Value: 0

    Column Name: CITY,
    Column Type: VARCHAR:
    Column Value: null

    Column Name: STATE,
    Column Type: VARCHAR:
    Column Value: BC

    Column Name: STREET,
    Column Type: VARCHAR:
    Column Value: null

    Column Name: ZIP,
    Column Type: VARCHAR:
    Column Value: null





Table Name: DEPARTMENT
 Row:
    Column Name: ID,
    Column Type: INTEGER:
    Column Value: 1

    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: Design





Table Name: PHONE
 Row:
    Column Name: ID,
    Column Type: BIGINT:
    Column Value: 1

    Column Name: NUMBER,
    Column Type: VARCHAR:
    Column Value: 111-111-1111

    Column Name: TYPE,
    Column Type: VARCHAR:
    Column Value: null

    Column Name: EMPLOYEE_ID,
    Column Type: INTEGER:
    Column Value: 0





Table Name: PROFESSOR
 Row:
    Column Name: ID,
    Column Type: INTEGER:
    Column Value: 0

    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: TOM

    Column Name: SALARY,
    Column Type: BIGINT:
    Column Value: 1111

    Column Name: STARTDATE,
    Column Type: DATE:
    Column Value: null

    Column Name: ADDRESS_ID,
    Column Type: INTEGER:
    Column Value: 0

    Column Name: DEPARTMENT_ID,
    Column Type: INTEGER:
    Column Value: 1

    Column Name: MANAGER_ID,
    Column Type: INTEGER:
    Column Value: null





Table Name: PROJECT




Table Name: PROJECT_PROFESSOR


 

标签:二百七十,return,String,示例,JPA,void,Column,import,public
From: https://blog.csdn.net/2301_78772942/article/details/142689114

相关文章

  • 最简单的示例:通过JDBC查询数据
    引言在现代企业级应用开发中,持久层框架(如MyBatis、Hibernate等)极大地简化了数据库操作,提高了开发效率和代码的可维护性。本文将通过一个最简单的示例,演示如何使用JDBC连接数据库、执行SQL语句以及处理结果,并与Mybatis源码做对比,为后续深入研究MyBatis源码打下基础......
  • 织梦数据库配置一个典型的 common.inc.php 文件中的数据库配置示例
    <?php//数据库配置$cfg_dbhost='localhost';//数据库服务器地址$cfg_dbport=3306;//数据库端口$cfg_dbase='your_database_name';//数据库名称$cfg_dbuser='your_username';//数据库用户名$cfg_dbpw='your_password';......
  • Mybatis-flex代替繁琐的JPA
    1.前言最近在新的SpringBoot项目中采用JPA来作为数据库的持久层。刚开始得益于Spring框架自带,IDEA也有丰富的支持;可以自行匹配数据库字段,接口中方法可以直接提示,支持JPQL,原生SQL等方式。写起来也是非常顺手。但是当业务中有一些复杂一点的需求,在JPA中实现就非常麻烦,且不直观。......
  • 分页使用示例
    1.代码classUserModelSerializer(serializers.ModelSerializer):role_display=UserRoleSerializer(many=True,source='roles',read_only=True)classMeta:model=models.Userfields=["id","username",&#......
  • 鸿蒙应用示例:镂空效果实现教程
    在鸿蒙系统中,为了给用户带来更加生动的视觉体验,我们可以使用不同的技术手段来实现图像和文字的镂空效果。本文将通过三个具体的示例来展示如何在鸿蒙系统中实现实心矩形镂空、实心圆镂空以及文字镂空的效果。示例代码//定义一个名为Index的应用入口组件@Entry@Componentstruct......
  • DataInOut 文件输入输出示例
    publicclassDataInOutTest{publicstaticvoidmain(String[]args){DataOutputStreamdos=null;DataInputStreamdis=null;FileInputStreamfis=null;FileOutputStreamfos=null;try{fis=newFileInp......
  • 鸿蒙应用示例:实现文本高亮与自动换行
    在设计应用界面时,我们常常需要对某些重要的文本进行高亮显示,以引起用户的注意。同时,在一些场景中,我们需要确保长文本能够自动换行,以适应不同的屏幕尺寸和布局需求。本文将通过两个示例,分别展示如何在HarmonyOS应用中实现这些功能。【示例一】文本高亮显示@Entry@Componentstruct......
  • 鸿蒙应用示例:ArkTS中设置颜色透明度与颜色渐变方案探讨
    /***根据比例混合两个十六进制颜色值。*@paramcolorA第一个颜色的十六进制值,例如红色'#ff0000'。*@paramcolorB第二个颜色的十六进制值,例如黑色'#000000'。*@paramratio混合比例,0表示仅返回colorA,1表示仅返回colorB,介于0和1之间的值会混合两个颜色。......
  • 鸿蒙应用示例:应用开发中的动态获取属性与调用方法技巧
    随着HarmonyOS的发展,API版本的更新带来了许多新的特性和限制。在API11及以后的版本中,直接赋值对象的语法不再被支持,这要求开发者们采用新的方式来处理对象的创建和属性的访问。同时,HarmonyOS支持ETS(EnhancedTypeScript)文件,这是一种扩展了TypeScript的文件格式,用于更好地支持Harmo......
  • 鸿蒙应用示例:NEXT 中 Map 类型的使用及注意事项
    在JavaScript中,Map对象允许存储任何类型的键和值,提供了键值对的存储功能。在HarmonyOS中,Map的使用基本遵循JavaScript的标准,尤其是要注意set赋值只能用get获取,而索引赋值只能用索引获取。且它们可以同时赋值但遍历的方式又不同。【Map对象的赋值与获取】使用set方法赋值当你需要......