学习笔记068——Hibernate框架介绍以及使用方法


主流 ORM 框架 Object Relation Mapping 对象关系映射,将面向对象映射成面向关系。

一、如何使用

1、导入相关依赖
2、创建 Hibernate 配置文件
3、创建实体类
4、创建实体类-关系映射文件
5、调用 Hibernate API 完成操作

二、具体操作

1、创建 Maven 工程,pom.xml

<dependencies>
    <!--简化实体类的开发-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.10</version>
    </dependency>

    <!--java连接mysql依赖-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.16</version>
    </dependency>
    
	<!--Hibernate依赖-->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.4.10.Final</version>
    </dependency>
</dependencies>

2、hibernate.cfg.xml

核心配置:session-factory

SessionFactory:针对单个数据库映射经过编译的内存镜像文件,将数据库转换为⼀个 Java 可以识别的镜像文件。

构建 SessionFactory 非常耗费资源,所以通常⼀个工程只需要创建⼀个 SessionFactory。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>
        <!--配置数据源-->
        <property name="connection.username">root</property>
        <property name="connection.password">password</property>
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate?serverTimezone=Asia/Shanghai&amp;useUnicode=true&amp;characterEncoding=UTF-8</property>
        <!--C3P0连接池-->
        <property name="hibernate.c3p0.acquire_increment">10</property>
        <property name="hibernate.c3p0.idle_test_period">10000</property>
        <property name="hibernate.c3p0.timeout">5000</property>
        <property name="hibernate.c3p0.max_size">30</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_statements">10</property>
        <!--是否输出底层SQL语句-->
        <property name="hibernate.show_sql">true</property>
        <!--输出底层SQL语句是否格式化-->
        <property name="hibernate.format_sql">true</property>
        <!--是否自动生成数据库-->
        <!--update:如果已经有表,更新;如果没有,创建。(一般用这个)-->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!--数据库方言-->
        <!--如果使用的mysql是5.x,写:org.hibernate.dialect.MySQL5Dialect。-->
        <!--如果使用的mysql是8.x,写:org.hibernate.dialect.MySQL8Dialect。-->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
        <!--注册实体关系映射文件-->
        <mapping resource="com/htl/entity/People.hbm.xml"/>
        <mapping resource="com/htl/entity/Customer.hbm.xml"/>
        <mapping resource="com/htl/entity/Orders.hbm.xml"/>
        <mapping resource="com/htl/entity/Account.hbm.xml"/>
        <mapping resource="com/htl/entity/Course.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

3、创建实体类

package com.htl.entity;

import lombok.Getter;
import lombok.Setter;

import java.util.Set;

@Getter
@Setter
public class Customer {
    private Integer id;
    private String name;
    private Set<Orders> orders;

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
package com.htl.entity;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Orders {
    private Integer id;
    private String name;
    private Customer customer;

    @Override
    public String toString() {
        return "Orders{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

4、创建实体关系映射文件

package com.htl.entity;

import lombok.Data;

@Data
public class People {
    private Integer id;
    private String name;
    private Double money;
}

在这里插入图片描述

People.hbm.xml

<?xml version="1.0"?>
        <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.htl.entity.People" table="people">
        <id name="id" type="java.lang.Integer">
            <column name="id"></column>
            <generator class="identity"></generator>
        </id>
        
        <property name="name" type="java.lang.String">
            <column name="name"></column>
        </property>

        <property name="money" type="java.lang.Double">
            <column name="money"></column>
        </property>
    </class>

</hibernate-mapping>

5、实体关系映射文件注册到 Hibernate 的配置文件中。

<!--注册实体关系映射文件-->
<mapping resource="com/htl/entity/People.hbm.xml"></mapping>

6、使用 Hibernate API 完成数据操作。

package com.htl.test;

import com.htl.entity.People;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test {
    public static void main(String[] args) {
        // 创建Configuration
        Configuration configuration = new Configuration().configure();
        /*如果默认是 hibernate.cfg.xml ,configure()里面就不用写。如果xml名字改了,里面就写修改的名字。*/
        System.out.println(configuration);
        // 获取SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        // 获取Session
        Session session = sessionFactory.openSession();
        // 向People表中插入数据
        People people = new People();
        people.setName("李四");
        people.setMoney(200.0);
        session.save(people);/*保存*/
        session.beginTransaction().commit();/*提交事务*/
        session.close();/*关闭session*/
    }
}

7、pom.xml 中需要配置 resource

<!--配置 resource-->
<!--能够识别读取java里面的xml文件-->
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
</build>

三、Hibernate 级联操作

1、一对多关系

客户和订单:每个客户可以购买多个产品,生成多个订单,但是一个订单只能属于一个客户,所以客户
是一,订单是多。

在这里插入图片描述

数据库中一的一方是主表,多的一方时候从表,通过主外键关系来维护。

面向对象中

package com.htl.entity;

import lombok.Getter;
import lombok.Setter;

import java.util.Set;

@Getter
@Setter
public class Customer {
    private Integer id;
    private String name;
    private Set<Orders> orders;

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
package com.htl.entity;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Orders {
    private Integer id;
    private String name;
    private Customer customer;

    @Override
    public String toString() {
        return "Orders{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

2、多对多关系

学生选课:一门课程可以被多个学生选择,一个学生可以选择多门课程,学生是多,课程也是多。

数据库中是通过两个一对多关系来维护的,学生和课程都是主表,额外增加⼀张中间表作为从表,两张
主表和中间表都是一对多关系。

在这里插入图片描述

面向对象中

package com.htl.entity;

import lombok.Getter;
import lombok.Setter;

import java.util.Set;

@Getter
@Setter
public class Account {
    private Integer id;
    private String name;
    private Set<Course> courses;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
package com.htl.entity;

import lombok.Getter;
import lombok.Setter;

import java.util.Set;

@Getter
@Setter
public class Course {
    private Integer id;
    private String name;
    private Set<Account> accounts;

    @Override
    public String toString() {
        return "Course{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

Java 和数据库对于这两种关系的体现完全是两种不同的方式,Hibernate 框架的作用就是将这两种方式进行转换和映射。

四、Hibernate 实现一对多

Customer.hbm.xml

<?xml version="1.0"?>
        <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.htl.entity.Customer" table="customer">
        <id name="id" type="java.lang.Integer">
            <column name="id"></column>
            <generator class="identity"></generator>
        </id>
        
        <property name="name" type="java.lang.String">
            <column name="name"></column>
        </property>
        
        <set name="orders" table="orders">
            <key column="cid"></key>
            <one-to-many class="com.htl.entity.Orders"></one-to-many>
        </set>
    </class> 

</hibernate-mapping>
  • set 标签来配置实体类中的集合属性 orsers
  • name 实体类属性名
  • table 表名
  • key 外键
  • one-to-many 与集合泛型的实体类对应

Orders.hbm.xml

<?xml version="1.0"?>
        <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.htl.entity.Orders" table="orders">
        <id name="id" type="java.lang.Integer">
            <column name="id"></column>
            <generator class="identity"></generator>
        </id>
        
        <property name="name" type="java.lang.String">
            <column name="name"></column>
        </property>
        
        <many-to-one name="customer" class="com.htl.entity.Customer" column="cid"></many-to-one>
    </class> 

</hibernate-mapping>
  • many-to-one 配置实体类对应的对象属性
  • name 属性名
  • class 属性对应的类
  • column 外键

需要在 Hibernate 配置文件中进行注册

<!-- 注册实体关系映射⽂件 -->
<mapping resource="com/htl/entity/Customer.hbm.xml"></mapping>
<mapping resource="com/htl/entity/Orders.hbm.xml"></mapping>

Hibernate API

package com.htl.test;

import com.htl.entity.Customer;
import com.htl.entity.Orders;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test2 {
    public static void main(String[] args) {
        //创建Configuration
        Configuration configuration = new Configuration().configure();
        /*如果默认是 hibernate.cfg.xml ,configure()里面就不用写。如果xml名字改了,里面就写修改的名字。*/
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();
        //创建Customer
        Customer customer = new Customer();
        customer.setName("张三11");
        //创建Orders
        Orders orders = new Orders();
        orders.setName("订单11");
        //建立关联关系
        orders.setCustomer(customer);
        //保存
        session.save(customer);
        session.save(orders);
        //提交事务
        session.beginTransaction().commit();
        //关闭
        session.close();
    }
}

五、Hibernate 实现多对多

Account.hbm.xml

<?xml version="1.0"?>
        <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.htl.entity.Account" table="t_account">
        <id name="id" type="java.lang.Integer">
            <column name="id"></column>
            <generator class="identity"></generator>
        </id>
        
        <property name="name" type="java.lang.String">
            <column name="name"></column>
        </property>
        
        <set name="courses" table="account_course">
            <key column="aid"></key>
            <many-to-many class="com.htl.entity.Course" column="cid"></many-to-many>
        </set>
    </class> 

</hibernate-mapping>

Course.hbm.xml

<?xml version="1.0"?>
        <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.htl.entity.Course" table="t_course">
        <id name="id" type="java.lang.Integer">
            <column name="id"></column>
            <generator class="identity"></generator>
        </id>
        
        <property name="name" type="java.lang.String">
            <column name="name"></column>
        </property>
        
        <set name="accounts" table="account_course">
            <key column="cid"></key>
            <many-to-many class="com.htl.entity.Account" column="aid"></many-to-many>
        </set>
    </class> 

</hibernate-mapping>
  • name 实体类对应的集合属性名
  • table 中间表名
  • key 外键
  • many-to-many 与集合泛型的实体类对应
  • column 属性与中间表的外键字段名对应

注册 Hibernate 配置文件中

<!--注册实体关系映射文件-->
<mapping resource="com/htl/entity/Account.hbm.xml"></mapping>
<mapping resource="com/htl/entity/Course.hbm.xml"></mapping>

Hibernate API

package com.htl.test;

import com.htl.entity.Account;
import com.htl.entity.Course;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

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

public class Test3 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        /*如果默认是 hibernate.cfg.xml ,configure()里面就不用写。如果xml名字改了,里面就写修改的名字。*/
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();
        Course course = new Course();
        course.setName("C语言");
        Account account = new Account();
        account.setName("李四");
        Set<Course> courses = new HashSet<Course>();
        courses.add(course);
        account.setCourses(courses);
        session.save(course);
        session.save(account);
        session.beginTransaction().commit();
        session.close();
    }
}

六、Hibernate 延迟加载

延迟加载、惰性加载、懒加载

使用延迟加载可以提⾼程序的运行效率,Java 程序与数据库交互的频次越低,程序运⾏的效率就越高,所以我们应该尽量减少 Java 程序与数据库的交互次数,Hibernate 延迟加载就很好的做到了这一点。

客户和订单,当我们查询客户对象时,因为有级联设置,所以会将对应的订单信息一并查询出来,这样就需要发送两条 SQL 语句,分别查询客户信息和订单信息。

延迟加载的思路是:当我们查询客户的时候,如果没有访问订单数据,只发送一条 SQL 语句查询客户信息,如果需要访问订单数据,则发送两条 SQLL。

延迟加载可以看作是⼀种优化机制,根据具体的需求,⾃动选择要执⾏的 SQL 语句数量。

1、一对多

1、查询 Customer,对 orders 进行延迟加载设置,在 customer.hbm.xml 进行设置,延迟加载默认开启。

<set name="orders" table="orders" lazy="true">
    <key column="cid"></key>
    <one-to-many class="com.htl.entity.Orders"></one-to-many>
</set>

2、查询 Customer

package com.htl.test;

import com.htl.entity.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test4 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        /*如果默认是 hibernate.cfg.xml ,configure()里面就不用写。如果xml名字改了,里面就写修改的名字。*/
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();
        
        Customer customer = session.get(Customer.class,6);
        System.out.println(customer);
        session.close();
    }
}

在这里插入图片描述

package com.htl.test;

import com.htl.entity.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test4 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        /*如果默认是 hibernate.cfg.xml ,configure()里面就不用写。如果xml名字改了,里面就写修改的名字。*/
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();
        
        Customer customer = session.get(Customer.class,6);
        System.out.println(customer.getOrders());
        session.close();
    }
}

在这里插入图片描述

在 customer.hbm.xml 中设置延迟加载关闭后

<set name="orders" table="orders" lazy="false">
    <key column="cid"></key>
    <one-to-many class="com.htl.entity.Orders"></one-to-many>
</set>
package com.htl.test;

import com.htl.entity.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test4 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        /*如果默认是 hibernate.cfg.xml ,configure()里面就不用写。如果xml名字改了,里面就写修改的名字。*/
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();
        
        Customer customer = session.get(Customer.class,6);
        System.out.println(customer);
        session.close();
    }
}

在这里插入图片描述

lazy 除了可以设置 true 和 false 之外,还可以设置 extra,extra 是比 true 更加懒惰的⼀种加载方式,或者说是更加智能的⼀种加载方式,通过例子看区别:

查询 Customer 对象,打印该对象对应的 orders 集合的长度。

在 customer.hbm.xml 中设置延迟加载为 extra 后。

<set name="orders" table="orders" lazy="extra">
    <key column="cid"></key>
    <one-to-many class="com.htl.entity.Orders"></one-to-many>
</set>
package com.htl.test;

import com.htl.entity.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test4 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        /*如果默认是 hibernate.cfg.xml ,configure()里面就不用写。如果xml名字改了,里面就写修改的名字。*/
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();
        
        Customer customer = session.get(Customer.class,6);
        System.out.println(customer.getOrders().size());
        session.close();
    }
}

在这里插入图片描述

也可以通过 Orders 来设置 Customer 的延迟加载,orders.hbm.xml 中进⾏设置。

<many-to-one name="customer" class="com.htl.entity.Customer" column="cid" lazy="proxy"></many-to-one>
package com.htl.test;

import com.htl.entity.Orders;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test5 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        Orders orders = session.get(Orders.class,2);
        System.out.println(orders);

        session.close();
    }
}

在这里插入图片描述

package com.htl.test;

import com.htl.entity.Orders;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test5 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        Orders orders = session.get(Orders.class,2);
        System.out.println(orders.getCustomer());
        
        session.close();
    }
}

在这里插入图片描述

no-proxy:当调用方法需要访问 customer 的成员变量时,发送 SQL 语句查询 Customer,否则不查询。

proxy:无论调用方法是否需要访问 customer 的成员变量,都会发送 SQL 语句查询 Customer。

2、多对多

1、查询 Course,加载对应的 Account,默认延迟加载开启。

在 Course.hbm.xml 里面,lazy 设置为 true。不写默认为 true。

<set name="accounts" table="account_course" lazy="true">
    <key column="cid"></key>
    <many-to-many class="com.htl.entity.Account" column="aid"></many-to-many>
</set>
package com.htl.test;

import com.htl.entity.Course;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test6 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        Course course = session.get(Course.class,1);
        System.out.println(course);
        session.close();
    }
}

在这里插入图片描述

package com.htl.test;

import com.htl.entity.Course;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test6 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        Course course = session.get(Course.class,1);
        System.out.println(course.getAccounts());
        session.close();
    }
}

在这里插入图片描述

在 Course.hbm.xml 里面,lazy 关闭,设置为 false 后,查看结果。

<set name="accounts" table="account_course" lazy="false">
    <key column="cid"></key>
    <many-to-many class="com.htl.entity.Account" column="aid"></many-to-many>
</set>
package com.htl.test;

import com.htl.entity.Course;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test6 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        Course course = session.get(Course.class,1);
        System.out.println(course);
        session.close();
    }
}

在这里插入图片描述

2、查询 Account,加载对应的 Course,默认延迟加载开启。

在 Account.hbm.xml 里面,lazy 设置为 true。不写默认为 true。

<set name="courses" table="account_course" lazy="true">
    <key column="aid"></key>
    <many-to-many class="com.htl.entity.Course" column="cid"></many-to-many>
</set>
package com.htl.test;

import com.htl.entity.Account;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test7 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        Account account = session.get(Account.class,1);
        System.out.println(account);
        session.close();
    }
}

在这里插入图片描述

package com.htl.test;

import com.htl.entity.Account;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test7 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        Account account = session.get(Account.class,1);
        System.out.println(account.getCourses());
        session.close();
    }
}

在这里插入图片描述

在 Account.hbm.xml 里面,lazy 关闭,设置为 false 后,查看结果。

<set name="courses" table="account_course" lazy="false">
    <key column="aid"></key>
    <many-to-many class="com.htl.entity.Course" column="cid"></many-to-many>
</set>
package com.htl.test;

import com.htl.entity.Account;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test7 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        Account account = session.get(Account.class,1);
        System.out.println(account);
        session.close();
    }
}

在这里插入图片描述

七、Hibernate 配置文件

  • hibernate.cfg.xml
  • hbm.xml

1、Hibernate.cfg.xml

hibernate.cfg.xml 配置 Hibernate 的全局环境。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>
        <!--配置数据源-->
        <property name="connection.username">root</property>
        <property name="connection.password">password</property>
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate?serverTimezone=Asia/Shanghai&amp;useUnicode=true&amp;characterEncoding=UTF-8</property>
        <!--C3P0连接池-->
        <property name="hibernate.c3p0.acquire_increment">10</property>
        <property name="hibernate.c3p0.idle_test_period">10000</property>
        <property name="hibernate.c3p0.timeout">5000</property>
        <property name="hibernate.c3p0.max_size">30</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_statements">10</property>
        <!--是否输出底层SQL语句-->
        <property name="hibernate.show_sql">true</property>
        <!--输出底层SQL语句是否格式化-->
        <property name="hibernate.format_sql">true</property>
        <!--是否自动生成数据库-->
        <!--update:如果已经有表,更新;如果没有,创建。(一般用这个)-->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!--数据库方言-->
        <!--如果使用的mysql是5.x,写:org.hibernate.dialect.MySQL5Dialect。-->
        <!--如果使用的mysql是8.x,写:org.hibernate.dialect.MySQL8Dialect。-->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
        <!--注册实体关系映射文件-->
        <mapping resource="com/htl/entity/People.hbm.xml"/>
        <mapping resource="com/htl/entity/Customer.hbm.xml"/>
        <mapping resource="com/htl/entity/Orders.hbm.xml"/>
        <mapping resource="com/htl/entity/Account.hbm.xml"/>
        <mapping resource="com/htl/entity/Course.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

<1>、数据库的基本信息。

<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate?serverTimezone=Asia/Shanghai&amp;useUnicode=true&amp;characterEncoding=UTF-8</property>

<2>、集成 C3P0,设置数据库连接池信息。

<property name="hibernate.c3p0.acquire_increment">10</property>
<property name="hibernate.c3p0.idle_test_period">10000</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.max_size">30</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_statements">10</property>

<3>、Hibernate 基本信息

<!--是否输出底层SQL语句-->
<property name="hibernate.show_sql">true</property>
<!--输出底层SQL语句是否格式化-->
<property name="hibernate.format_sql">true</property>
<!--是否自动生成数据库-->
<!--update:如果已经有表,更新;如果没有,创建。(一般用这个)-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--数据库方言-->
<!--如果使用的mysql是5.x,写:org.hibernate.dialect.MySQL5Dialect。-->
<!--如果使用的mysql是8.x,写:org.hibernate.dialect.MySQL8Dialect。-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>

<-是否自动生成数据库->里面可填的几个值:

  • update:动态创建表,如果表存在,则直接使用,如果表不存在,则创建。
  • create:无论表是否存在,都会重新创建。
  • create-drop:初始化创建表,程序结束时删除表。
  • validate:校验实体关系映射文件和数据表是否对应,不能对应直接报错。

<4>、注册实体关系映射文件

<mapping resource="com/htl/entity/People.hbm.xml"></mapping>
<mapping resource="com/htl/entity/Customer.hbm.xml"></mapping>
<mapping resource="com/htl/entity/Orders.hbm.xml"></mapping>
<mapping resource="com/htl/entity/Account.hbm.xml"></mapping>
<mapping resource="com/htl/entity/Course.hbm.xml"></mapping>

2、hbm.xml

称为:实体关系映射文件

<?xml version="1.0"?>
        <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.htl.entity.Course" table="t_course">
        <id name="id" type="java.lang.Integer">
            <column name="id"></column>
            <generator class="identity"></generator>
        </id>
        
        <property name="name" type="java.lang.String">
            <column name="name"></column>
        </property>
        
        <set name="accounts" table="account_course" lazy="true">
            <key column="cid"></key>
            <many-to-many class="com.htl.entity.Account" column="aid"></many-to-many>
        </set>
    </class> 

</hibernate-mapping>

<1>、hibernate-mapping 属性

  • package:给 class 节点对应的实体类统一设置包名,此处设置包名,class 的 name 属性就可以省略包名。

如上面的实体映射文件修改为下面的:

  <?xml version="1.0"?>
          <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  <hibernate-mapping package="com.htl.entity">
  
      <class name="Course" table="t_course">
          <id name="id" type="java.lang.Integer">
              <column name="id"></column>
              <generator class="identity"></generator>
          </id>
          
          <property name="name" type="java.lang.String">
              <column name="name"></column>
          </property>
          
          <set name="accounts" table="account_course" lazy="true">
              <key column="cid"></key>
              <many-to-many class="Account" column="aid"></many-to-many>
          </set>
      </class> 
  
  </hibernate-mapping>
  • schema:数据库 schema 的名称。

  • catalog:数据库 catalog 的名称。

  • default-cascade:默认的级联关系,默认为 none。

  • default-access:Hibernate 用来访问属性的策略。

  • default-lazy:指定了未明确注明 lazy 属性的 Java 属性和集合类,Hibernate 会采用什么样的加载风格,默认为 true 。

  • auto-import:指定我们是否可以在查询语句中使用非全限定类名,默认为 true,如果项目中有两个同名的持久化类,最好在这两个类的对应映射文件中配置为 false。

<2>、class 属性

  • name:实体类名
  • table:数据表名
  • schema:数据库 schema 的名称,会覆盖 hibernate-mapping 的 schema
  • catalog:数据库 catalog 的名称,会覆盖 hibernate-mapping 的 catalog
  • proxy:指定⼀个接口,在延迟加载时作为代理使用
  • dynamic-update:动态更新(默认关闭)
  • dynamic-insert:动态添加(默认关闭)

当没有开启动态加载(dynamic-insert)时,只设置 name 的值,没有赋值的 money 也会默认赋 null 存入。两个都存。(有多少属性存多少属性)

package com.htl.test;

import com.htl.entity.People;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test8 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        People people = new People();
        people.setName("张三");
        session.save(people);
        session.close();
    }
}

在这里插入图片描述

当开启动态加载(dynamic-insert)后,只设置 name 的值,则只存 name ,其余不存:

<class name="com.htl.entity.People" table="people" dynamic-insert="true">

在这里插入图片描述

当没有开启动态更新(dynamic-update),更新 money 时,update语句连同 name 一块更新了。

package com.htl.test;

import com.htl.entity.People;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test8 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        People people = session.get(People.class,6);
        people.setMoney(2000.0);
        session.update(people);
        session.beginTransaction().commit();
        session.close();
    }
}

在这里插入图片描述

当开启动态更新(dynamic-update)后,更新 money 时,update语句不会连同 name 一块更新。

<class name="com.htl.entity.People" table="people" dynamic-insert="true" dynamic-update="true">
package com.htl.test;

import com.htl.entity.People;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test8 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        People people = session.get(People.class,7);
        people.setMoney(7000.0);
        session.update(people);
        session.beginTransaction().commit();
        session.close();
    }
}

在这里插入图片描述

  • where:查询时给 SQL 添加 where 条件(默认关闭)

当没加 where 时:

package com.htl.test;

import com.htl.entity.People;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.List;

public class Test8 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        String hql = "from People";
        Query query = session.createQuery(hql);
        List<People> list = query.list();
        for (People people :
                list) {
            System.out.println(people);
        }
        session.beginTransaction().commit();
        session.close();
    }
}

在这里插入图片描述

加了 where 后,可以用 where 约束查询结果。

<class name="com.htl.entity.People" table="people" dynamic-insert="true" dynamic-update="true" where="id = 6">

运行语句同上。

在这里插入图片描述

<3>、id 属性

  • name:实体类属性名
  • type:实体类属性数据类型

此处可以设置两种类型的数据:Java 数据类型或者 Hibernate 映射类型。

实体类的属性数据类型必须与数据表对应的字段数据类型一致:

int 对应 int,String 对应 varchar

如何进行映射?

Java 数据类型映射到 Hibernate 映射类型,再由 Hibernate 映射类型映射到 SQL 数据类型

Java —》Hibernate —〉SQL

  • column:数据表的主键字段名
  • generator:主键生成策略

1、hilo 算法

2、increment:Hibernate 自增

3、identity:数据库自增

4、native:本地策略,根据底层数据库自动选择主键的生成策略

5、uuid.hex 算法

6、select 算法

<4>、property 属性

  • name:实体类的属性名
  • column:数据表字段名
  • type:数据类型
  • update:该字段是否可以修改,默认为 true
  • insert:该字段是否可以添加,默认为 true
  • lazy:延迟加载策略

<5>、实体关系映射文件属性

1、inverse

inverse 属性是用来设置是否将维护权交给对方,默认是 false,不交出维护权,双方都在维护,将它设置为 true,表示放弃维护。

Customer 和 Orders 是一对多关系,一个 Customer 对应多个 Orders,实体类中用一个 set 集合来表示对应的 Orders。

package com.htl.entity;

import lombok.Getter;
import lombok.Setter;

import java.util.Set;

@Getter
@Setter
public class Customer {
    private Integer id;
    private String name;
    private Set<Orders> orders;

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

Customer.hbm.xml 中使用 set 标签来配置映射关系。

<?xml version="1.0"?>
        <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.htl.entity.Customer" table="customer">
        <id name="id" type="java.lang.Integer">
            <column name="id"></column>
            <generator class="identity"></generator>
        </id>
        
        <property name="name" type="java.lang.String">
            <column name="name"></column>
        </property>
        
        <set name="orders" table="orders" lazy="true">
            <key column="cid"></key>
            <one-to-many class="com.htl.entity.Orders"></one-to-many>
        </set>
    </class> 

</hibernate-mapping>

实体类

package com.htl.entity;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Orders {
    private Integer id;
    private String name;
    private Customer customer;

    @Override
    public String toString() {
        return "Orders{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

Orders.hbm.xml

<?xml version="1.0"?>
        <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.htl.entity.Orders" table="orders">
        <id name="id" type="java.lang.Integer">
            <column name="id"></column>
            <generator class="identity"></generator>
        </id>
        
        <property name="name" type="java.lang.String">
            <column name="name"></column>
        </property>
        
        <many-to-one name="customer" class="com.htl.entity.Customer" column="cid" lazy="proxy"></many-to-one>
    </class> 

</hibernate-mapping>
package com.htl.test;

import com.htl.entity.Customer;
import com.htl.entity.Orders;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test9 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        Customer customer = new Customer();
        customer.setName("李四");

        Orders orders1 = new Orders();
        orders1.setName("订单4");
        orders1.setCustomer(customer);

        Orders orders2 = new Orders();
        orders2.setName("订单44");
        orders2.setCustomer(customer);

        session.save(customer);
        session.save(orders1);
        session.save(orders2);

        session.beginTransaction().commit();
        session.close();
    }
}

3条SQL执行语句。

在这里插入图片描述

当添加Customer维护后,(此时Customer和Orders双方都在维护)

package com.htl.test;

import com.htl.entity.Customer;
import com.htl.entity.Orders;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

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

public class Test9 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        Customer customer = new Customer();
        customer.setName("王5");

        Orders orders1 = new Orders();
        orders1.setName("5");
        orders1.setCustomer(customer);

        Orders orders2 = new Orders();
        orders2.setName("55");
        orders2.setCustomer(customer);

        //添加Customer维护
        Set<Orders> orders = new HashSet<Orders>();
        orders.add(orders1);
        orders.add(orders2);
        customer.setOrders(orders);

        session.save(customer);
        session.save(orders1);
        session.save(orders2);

        session.beginTransaction().commit();
        session.close();
    }
}

5条SQL执行语句。

在这里插入图片描述

在这里插入图片描述

因为 Customer 和 Orders 都在维护一对多关系,所以会重复设置主外键约束关系。

如何避免这种情况?
1、在 Java 代码中去掉一方维护关系代码。
2、通过配置来解决。

Customer.hbm.xml

<set name="orders" table="orders" lazy="true" inverse="true">
    <key column="cid"></key>
    <one-to-many class="com.htl.entity.Orders"></one-to-many>
</set>

将 inverse 置为 true,表示 Customer 放弃维护。

再运行:

package com.htl.test;

import com.htl.entity.Customer;
import com.htl.entity.Orders;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

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

public class Test9 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        Customer customer = new Customer();
        customer.setName("王5");

        Orders orders1 = new Orders();
        orders1.setName("5");
        orders1.setCustomer(customer);

        Orders orders2 = new Orders();
        orders2.setName("55");
        orders2.setCustomer(customer);

        //添加Customer维护
        Set<Orders> orders = new HashSet<Orders>();
        orders.add(orders1);
        orders.add(orders2);
        customer.setOrders(orders);

        session.save(customer);
        session.save(orders1);
        session.save(orders2);

        session.beginTransaction().commit();
        session.close();
    }
}

3条SQL执行语句。

在这里插入图片描述

2、cascade

用来设置级联操作。

正常删除有外键约束的表里面的数据时,会报错。

package com.htl.test;

import com.htl.entity.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test10 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        //删除
        Customer customer = session.get(Customer.class,7);
        session.delete(customer);
        session.beginTransaction().commit();
        session.close();
    }
}

在这里插入图片描述

想要删除有外键约束的表里面的数据的方法如下,

方法一:

package com.htl.test;

import com.htl.entity.Customer;
import com.htl.entity.Orders;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.util.Iterator;

public class Test10 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        //删除
        Customer customer = session.get(Customer.class,7);
        Iterator<Orders> iterator = customer.getOrders().iterator();
        while (iterator.hasNext()){
            session.delete(iterator.next());
        }
        session.delete(customer);
        session.beginTransaction().commit();
        session.close();
    }
}

在这里插入图片描述

在这里插入图片描述

方法二:

实体关系映射⽂件中设置 cascade 值完成级联删除。

Customer.hbm.xml

<set name="orders" table="orders" lazy="true" inverse="true" cascade="delete">
    <key column="cid"></key>
    <one-to-many class="com.htl.entity.Orders"></one-to-many>
</set>

然后不需要再迭代,直接就能删除了。

package com.htl.test;

import com.htl.entity.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test10 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        //删除
        Customer customer = session.get(Customer.class,7);
        session.delete(customer);
        session.beginTransaction().commit();
        session.close();
    }
}

在这里插入图片描述

在这里插入图片描述

八、Hibernate HQL

HQL:Hibernate Query Language,是 Hibernate 框架提供的一种查询机制,它和 SQL 类似,不同的是 HQL 是面向对象的查询语句,让开发者能够以面向对象的思想来编写查询语句,对 Java 编程是一种很友好的方式。

HQL 不能直接参与数据库的交互,它是中间层语⾔。

Java —》HQL —〉Hibernate —》SQL —〉DB

HQL 只能完成查询修改删除新增是无法操作的

1、查询对象

查询表中所有数据,自动完成对象的封装,返回 List 集合。

HQL 进行查询,from 关键字后面不能写表名,必须写表对应的实体类名。

package com.htl.test;

import com.htl.entity.People;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.List;

public class Test11 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        //查询对象
        String hql = "from People ";
        /* 写的是所查询表对应的实体类的名字!尽量写实体类的全类名。也就是 from com.htl.entity.People */
        Query query = session.createQuery(hql);
        List<People> list = query.list();
        for (People people:list){
            System.out.println(people);
        }
        session.close();
    }
}

注意:People.hbm.xml 里面的 where=“id = 6” 要去掉。这样才能查询出完整的 People 表里面的数据。

在这里插入图片描述

2、分页查询

HQL 分页查询可以通过调用 query 的方法来完成。

1、setFirstResult() 设置起始下标

2、setMaxResults() 设置截取长度

package com.htl.test;

import com.htl.entity.People;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.List;

public class Test12 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();
        //分页查询
        String hql = "from com.htl.entity.People";
        Query query = session.createQuery(hql);
        query.setFirstResult(1);
        query.setMaxResults(3);
        /* 截取People表里面第2个到第4个的数据。*/
        List<People> list = query.list();
        for (People people:list){
            System.out.println(people);
        }
        session.close();
    }
}

在这里插入图片描述

3、where 条件查询

HQL 直接追加 where 关键字作为查询条件,与 SQL 没有区别。

package com.htl.test;

import com.htl.entity.People;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

public class Test13 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        //where条件查询
        String hql = "from People where id = 6";
        Query query = session.createQuery(hql);
        People people = (People) query.list().get(0);
        System.out.println(people);
        session.close();
    }
}

query.list() 返回一个集合,此时集合中只有一个对象,通过下标 0 取出该对象。

在这里插入图片描述

当表里面没有符合where查询条件的数据时,query调用uniqueResult()方法时,就不会抛出异常,而是返回null 。

String hql = "from People where id = 0";
Query query = session.createQuery(hql);
People people = (People) query.uniqueResult();
System.out.println(people);

在这里插入图片描述

4、模糊查询

查询名称包含“三”的所有记录。

package com.htl.test;

import com.htl.entity.People;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.List;

public class Test14 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        //模糊查询
        String hql = "from People where name like '%三%'";
        Query query = session.createQuery(hql);
        List<People> list = query.list();
        for (People people:list){
            System.out.println(people);
        }
        session.close();
    }
}

在这里插入图片描述

5、order by

按照 id 进行排序。

asc 是生序排列,desc 是降序排列。

package com.htl.test;

import com.htl.entity.People;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.List;

public class Test15 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        String hql = "from People order by id";
        /* 默认是 asc 升序。*/
        Query query = session.createQuery(hql);
        List<People> list = query.list();
        for (People people:list){
            System.out.println(people);
        }
        session.close();
    }
}

在这里插入图片描述

降序:

String hql = "from People order by id desc ";

在这里插入图片描述

6、查询实体对象的属性

package com.htl.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

public class Test16 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        //查询实体对象的属性
        String hql = "select name from People where id = 6";
        Query query = session.createQuery(hql);
        String name = (String) query.uniqueResult();
        System.out.println(name);
        session.close();
    }
}

在这里插入图片描述

7、占位符

package com.htl.test;

import com.htl.entity.People;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.List;

public class Test17 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        //占位符
        String hql = "from People where name = :name";
        Query query = session.createQuery(hql);
        query.setString("name","张三0");
        List<People> list = query.list();
        for (People people:list){
            System.out.println(people);
        }
        session.close();
    }
}

在这里插入图片描述

8、级联查询

package com.htl.test;

import com.htl.entity.Customer;
import com.htl.entity.Orders;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.List;

public class Test18 {
    public static void main(String[] args) {
        //创建 Configuration
        Configuration configuration = new Configuration().configure();
        //获取 SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取 Session
        Session session = sessionFactory.openSession();

        //级联查询
        String hql = "from Customer where name = :name";
        Query query1 = session.createQuery(hql);
        query1.setString("name","李四");
        Customer customer = (Customer) query1.uniqueResult();
        String hql2 = "from Orders where customer = :customer";
        Query query2 = session.createQuery(hql2);
        query2.setEntity("customer",customer);
        List<Orders> list = query2.list();
        for (Orders orders:list){
            System.out.println(orders);
        }
        session.close();
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值