Hibernate's HQL database operation

File structure

Insert picture description here

1. Entity class instance Employee

package com.bdqn.entity;

import java.util.Date;

public class Employee {
    
    
    private Integer empNo;      //员工编号
    private String empName;     //员工姓名
    private String job;         // 职位
    private Double salary;      // 薪资
    private Integer deptNo;     // 部门编号
    private Date hireDate;      // 入职时间

//    public Employee(String empName,String job, Double salary,Integer deptNo,Date hireDate){
    
    
//        this.empName = empName;
//        this.job = job;
//        this.salary = salary;
//        this.deptNo = deptNo;
//        this.hireDate = hireDate;
//    }

    public Integer getEmpNo() {
    
    
        return empNo;
    }

    public String getEmpName() {
    
    
        return empName;
    }

    public String getJob() {
    
    
        return job;
    }

    public Double getSalary() {
    
    
        return salary;
    }

    public Integer getDeptNo() {
    
    
        return deptNo;
    }

    public Date getHireDate() {
    
    
        return hireDate;
    }

    public void setEmpNo(Integer empNo) {
    
    
        this.empNo = empNo;
    }

    public void setEmpName(String empName) {
    
    
        this.empName = empName;
    }

    public void setJob(String job) {
    
    
        this.job = job;
    }

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

    public void setDeptNo(Integer deptNo) {
    
    
        this.deptNo = deptNo;
    }

    public void setHireDate(Date hireDate) {
    
    
        this.hireDate = hireDate;
    }

    @Override
    public String toString() {
    
    
        return "Employee{" +
                "empNo=" + empNo +
                ", empName='" + empName + '\'' +
                ", job='" + job + '\'' +
                ", salary=" + salary +
                ", deptNo=" + deptNo +
                ", hireDate=" + hireDate +
                '}';
    }
}

2. The utils class converts the string into Date format

File name: DateUtil.class

package com.bdqn.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.ParseException;

public class DateUtil {
    
    

    /**
     * 将字符创转换成 Date 日期格式
     * @param str
     * @return
     * */
    public static Date formatDate(String str){
    
    
        try{
    
    
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            return format.parse(str);
        } catch (ParseException e){
    
    
            e.fillInStackTrace();
        }
        return null;
    }

}

3. Expand entity EmployeeVo

com.xxx.vo.EmployeeVo.class
will automatically generate fields without

package com.bdqn.vo;

import com.bdqn.entity.Employee;

import java.util.Date;
import java.util.zip.DataFormatException;

/**
 * 自定义查询类
 * 该类制作查询条件的参数(方法参数),不做方法的返回值类型
 * */
public class EmployeeVo extends Employee {
    
    

    // 开始时间
    private Date startDate;
    // 结束时间
    private Date endDate;

    public Date getStartDate() {
    
    
        return startDate;
    }

    public Date getEndDate() {
    
    
        return endDate;
    }

    public void setStartDate(Date startDate) {
    
    
        this.startDate = startDate;
    }

    public void setEndDate(Date endDate) {
    
    
        this.endDate = endDate;
    }
}

4. Increase

5. Delete

6. Change

6.1

/**
* 按位置进行参数绑定
*      注意:高版本hibernate下标从1开始
* */
@Test
public void testParamter1(){
    
    
    // 获取Session
    Session session = HibernateUtil.getSession();
    // 定义HQL语句
    String hql = "from Employee where empName like ?1 and salary >= ?2";
    // 创建Query对象
    Query query = session.createQuery(hql);
    // 赋值
//        query.setString(1,"%国%");
//        query.setDouble(1,5000);
    // 推荐使用 setParameter()
    query.setParameter(1,"%国%");
    query.setParameter(2,5000.0);

    // 执行查询
    List<Employee> list = query.list();
    for (Employee employee : list) {
    
    
        System.out.println(employee);
    }
}

6.2

 /**
     *
     * */
    @Test
    public void testParamter2(){
    
    
        // 获取Session
        Session session = HibernateUtil.getSession();
        // 定义HQL语句
        String hql = "from Employee where empName like :empName and salary >= :salary";
        // 创建Query对象
        Query query = session.createQuery(hql);
        // 赋值
//        query.setString(1,"%国%");
//        query.setDouble(1,5000);
        // 推荐使用 setParameter()
        query.setParameter("empName","%国%");
        query.setParameter("salary",5000.0);

        // 执行查询
        List<Employee> list = query.list();
        for (Employee employee : list) {
    
    
            System.out.println(employee);
        }
    }

7. Check

7.1 list()

/**
* 查询所有员工列表
* */
@Test
public void testList(){
    
    
    // 获取Session(使用openSession()方式获取)
    Session session = HibernateUtil.getSession();
    try{
    
    
        // 定义HQl语句  查询的是实体类类名
        String hql = "from Employee";
        // 创建Query对象
        Query query = session.createQuery(hql);
        // 执行查询
        List<Employee> list = query.list();
        // 循环遍历
        for (Employee employee : list) {
    
        // 快捷键: iter
            System.out.println(employee);
        }
    } catch (Exception e){
    
    
        e.printStackTrace();
    } finally {
    
    
        // 关闭资源
        HibernateUtil.closeSession(session);
    }
}

7.2 iterate()

/**
* 查询所有员工列表
* */
@Test
public void testIternate(){
    
    
    // 获取Session(使用openSession()方式获取)
    Session session = HibernateUtil.getSession();
    try{
    
    
        // 定义HQl语句  查询的是实体类类名
        String hql = "from Employee";
        // 创建Query对象
        Query query = session.createQuery(hql);
        // 执行查询
        Iterator<Employee> iterate = query.iterate(); // 会发出1+N田sql语句
        //循环遍历
        while(iterate.hasNext()) {
    
    
            // 得到每一个员工对象
            Employee employee = iterate.next();
            System.out.println(employee);
        }
    } catch (Exception e){
    
    
        // 关闭资源
        HibernateUtil.closeSession(session);
    }
}

7.3 Dynamic condition query

/**
* 动态条件查询
* */
@Test
public void testEmployee(){
    
    

    // 创建查询条件类对象
    EmployeeVo employeeVo = new EmployeeVo();
    employeeVo.setJob("python程序员");
    employeeVo.setStartDate(DateUtil.formatDate("2018-01-01"));
    employeeVo.setEndDate(DateUtil.formatDate("2021-01-01"));

    // 获取 Session
    Session session = HibernateUtil.getSession();
    // 定义 sql 语句
    StringBuilder hql = new StringBuilder("from Employee where 1=1 ");
    // 判断条件是否为空
    if(employeeVo != null){
    
    
        // 薪资
        if(employeeVo.getSalary() != null){
    
    
            hql.append(" and salary >= :salary"); // 命名参数必须与实体类的属性名相同
        }
        // 职位
        if(employeeVo.getJob() != null && employeeVo.getJob().equals("")){
    
    
            hql.append(" and job = :job");      // 命名参数必须与实体类的属性名相同
        }
        // 开始时间
        if(employeeVo.getStartDate() != null){
    
    
            hql.append(" and hireDate >= startDate");
        }
        // 结束时间
        if(employeeVo.getEndDate() != null){
    
    
            hql.append(" and hireDate <= :endDate");
        }
    }
    // 创建 query 对象
    Query query = session.createQuery(hql.toString());
    // 赋值
    query.setProperties(employeeVo);//要求:必须保证命名擦书名称与实体类的属性名相同
    // 执行查询
    List<Employee> list = query.list();
    for (Employee employee : list) {
    
    
        System.out.println(employee);
    }

}

Guess you like

Origin blog.csdn.net/zx77588023/article/details/109501717