Hibernate学习笔记

Posted 最小的帆也能远航

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate学习笔记相关的知识,希望对你有一定的参考价值。

目录

1.一对一关系 

2.一对多关系

3.多对多关系


官网:Hibernate 中文文档 | Hibernate 中文网

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

如何使⽤

1、导⼊相关依赖

2、创建 Hibernate 配置⽂件

3、创建实体类

4、创建实体类-关系映射⽂件

5、调⽤ Hibernate API 完成操作

1.一对一关系 

具体操作

1、创建 Maven ⼯程,pom.xml 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>hibernateDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.5.8.Final</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

2hibernate.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">root</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false</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>
        <!-- 数据库⽅⾔ -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 打印SQL -->
        <property name="show_sql">true</property>
        <!-- 格式化SQL -->
        <property name="format_sql">true</property>
        <!-- 是否⾃动⽣成数据库 -->
        <property name="hibernate.hbm2ddl.auto"></property>
        <!-- 注册实体关系映射⽂件 -->
        <mapping resource="com/newer/xxh/People.hbm.xml"></mapping>
        <mapping resource="com/newer/xxh/Customer.hbm.xml"></mapping>
        <mapping resource="com/newer/xxh/Orders.hbm.xml"></mapping>
        <mapping resource="com/newer/xxh/Account.hbm.xml"></mapping>
        <mapping resource="com/newer/xxh/Course.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

 3、创建实体类

package com.newer.xxh;

import lombok.Data;

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

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

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN"
                "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.newer.xxh.People" table="people" dynamic-insert="true" dynamic-update="true" >
        <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/newer/xxh/People.hbm.xml"></mapping>

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

import com.newer.xxh.*;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.Iterator;
import java.util.List;


public class Test {
    public static void main(String[] args) {
        Configuration configuration = new Configuration().configure();
        Session session = configuration.buildSessionFactory().openSession();
        People people = new People();
        people.setName("马哥");
        people.setMoney(200.2);
        session.save(people);
        session.beginTransaction().commit();
        session.close();
    }
}

 

 

以上就是最简单的一对一的。如果出现路径问题,可以考虑

 <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

也可以参考:【Hibernate】Access to DialectResolutionInfo cannot be null when ‘hibernate.dialect‘ not set_北有孤酒的博客-CSDN博客


2.一对多关系

客户和订单:

每个客户可以购买多个产品,⽣成多个订单,但是⼀个订单只能属于⼀个客户,所以客户 是⼀,订单是多

customer表

 orders表

 Customer

package com.newer.xxh;

import lombok.Data;

import java.util.Set;

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

}

 Customer.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.newer.xxh.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" inverse="true" cascade="delete">
           <key column="cid"></key>
           <one-to-many class="com.newer.xxh.Orders"></one-to-many>
       </set>
    </class>
</hibernate-mapping>
  • set 标签来配置实体类中的集合属性 orders
  • name 实体类属性名
  • table 表名
  • key 外键
  • one-to-many 与集合泛型的实体类对应

 Orders

package com.newer.xxh;

import lombok.Data;

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

}

Orders.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.newer.xxh.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.newer.xxh.Customer" column="cid"></many-to-one>
    </class>
</hibernate-mapping>
  • many-to-one 配置实体类对应的对象属性
  • name 属性名
  • class 属性对应的类column 外键
 <!-- 注册实体关系映射⽂件 -->
 <mapping resource="com/newer/xxh/Customer.hbm.xml"></mapping>
 <mapping resource="com/newer/xxh/Orders.hbm.xml"></mapping>
import com.newer.xxh.*;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.Iterator;
import java.util.List;


public class Test {
    public static void main(String[] args) {
        Configuration configuration = new Configuration().configure();
        Session session = configuration.buildSessionFactory().openSession();
        //创建 Customer
        Customer customer = new Customer();
        customer.setName("张三");
        //创建 Orders
        Orders orders = new Orders();
        orders.setName("订单1");
        //建⽴关联关系
        orders.setCustomer(customer);

        //保存
        session.save(customer);
        session.save(orders);
        session.beginTransaction().commit();
        session.close();
    }
}

 


3.多对多关系

学⽣选课:⼀⻔课程可以被多个学⽣选择,⼀个学⽣可以选择多⻔课程,学⽣是多,课程也是多。

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

account表

course表 

 

account_course表 

 

 Account

package com.newer.xxh;

import lombok.Data;

import java.util.Set;

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

Account.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.newer.xxh.Account" table="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="cid"></key>
            <many-to-many class="com.newer.xxh.Course" column="aid"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

Course

package com.newer.xxh;

import lombok.Data;

import java.util.Set;

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

Course.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.newer.xxh.Course" table="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="aid"></key>
            <many-to-many class="com.newer.xxh.Account" column="cid"></many-to-many>
        </set>
    </class>
</hibernate-mapping>
 <!-- 注册实体关系映射⽂件 -->
 <mapping resource="com/newer/xxh/Account.hbm.xml"></mapping>
 <mapping resource="com/newer/xxh/Course.hbm.xml"></mapping>
import com.newer.xxh.*;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

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


public class Test {
    public static void main(String[] args) {
        Configuration configuration = new Configuration().configure();
        Session session = configuration.buildSessionFactory().openSession();
        Course course = new Course();
        course.setName("python");
        Account account = new Account();
        account.setName("李四");
        Set<Course> courses = new HashSet<>();
        courses.add(course);
        account.setCourses(courses);
        session.save(course);
        session.save(account);
        session.beginTransaction().commit();
        session.close();
    }
}

 

  

以上是关于Hibernate学习笔记的主要内容,如果未能解决你的问题,请参考以下文章

Hibernate学习笔记

hibernate学习笔记之一 hibernate简介

框架学习笔记之Hibernate

HIbernate学习笔记 之 简介

[原创]java WEB学习笔记83:Hibernate学习之路---双向 1-n介绍,关键点解释,代码实现,set属性介绍(inverse,cascade ,order-by )

Hibernate学习笔记_02