hibernate快速入门(一)

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

如何使用:

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

具体操作:

概览:

 

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>com.southwind</groupId>
    <artifactId>hibernate</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.19</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.10.Final</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
    </dependencies>

    <!--这个是为了允许读取到src下面的xml文件-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

2、编写hibernate.cfg.xml文件

<?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-->
<!--    SessionFactory:针对单个数据库映射经过编译的内存镜像⽂件,将数据库转换为⼀个 Java 可以识别的镜像⽂件。-->
<!--    构建 SessionFactory ⾮常耗费资源,所以通常⼀个⼯程只需要创建⼀个 SessionFactory。-->
    <session-factory>
        <!-- datasource 数据源配置 -->
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT</property>
<!--?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT" />-->

        <!-- C3P0 连接池 -->
        <property name="hibernate.c3p0.acquire_increment">10</property>    <!-- 每次不够的话就会增加的数量-->
        <property name="hibernate.c3p0.idle_test_period">10000</property>  <!--释放资源时间的设置,s为单位-->
        <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>       <!-- 最大线程数数-->
        <!-- 数据库⽅⾔ oracle或mysql-->
        <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">update</property>
        <!-- create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,
                     哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
             create-drop :每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
             update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),
                     以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。
                     要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。
             validate :每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
             -->

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

    </session-factory>
</hibernate-configuration>

3、创建实体类和创建实体关系映射⽂件:

##1、Customer实体类:

@Getter
@Setter
public class Customer {
    private Integer id;
    private String  name;
    private Set<Orders> orders;  //将多个order都注入到customer里面了

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

##2、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> <!--文件名的hbm就是hibernate-mapping 的缩写,在这里面完成类和表的映射-->

    <!-- class 就是指类,name就是指类名 table 就是指对应的表名,表customer里面有id和name两个字段-->
    <class name="com.southwind.entity.Customer" table="customer">
       <!-- 主键映射 name指的是实体类里面的属性:id   type指的是id属性的类型-->
        <id name="id" type="java.lang.Integer">
            <!--column是字段,指的是对应类里面id的表里面的名称-->
            <column name="id"></column>
            <!--这个是配置主键自增的方式,identity的意思就是自增-->
            <generator class="identity"></generator>
        </id>
        <!-- 下面继续配置类里面的其他信息,name   type指的是name属性的类型-->
        <property name="name" type="java.lang.String">
            <!--column是字段,指的是对应类里面name的表里面的名称-->
            <column name="name"></column>
        </property>

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

    </class>

</hibernate-mapping>

##3、People实体类:

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

##4、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> <!--文件名的hbm就是hibernate-mapping 的缩写,在这里面完成类和表的映射-->

    <!-- class 就是指类,name就是指类名 table 就是指对应的表名,表customer里面有id和name两个字段-->
    <class name="com.southwind.entity.People" table="people">
       <!-- 主键映射 name指的是实体类里面的属性:id   type指的是id属性的类型-->
        <id name="id" type="java.lang.Integer">
            <!--column是字段,指的是对应类里面id的表里面的名称-->
            <column name="id"></column>
            <!--这个是配置主键自增的方式,identity的意思就是自增-->
            <generator class="identity"></generator>
        </id>
        <!-- 下面继续配置类里面的其他信息,name   type指的是name属性的类型-->
        <property name="name" type="java.lang.String">
            <!--column是字段,指的是对应类里面name的表里面的名称-->
            <column name="name"></column>
        </property>
        <!-- 下面继续配置类里面的其他信息,money   type指的是money属性的类型-->
        <property name="money" type="java.lang.Double">
            <!--column是字段,指的是对应类里面money的表里面的名称-->
            <column name="money"></column>
        </property>

    </class>

</hibernate-mapping>

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

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

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

package com.southwind.test;

import com.southwind.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,即配置类对象 默认的是去读hibernate.cfg.xml,
        // 不然你就在下面一行最后面这样写:.configure("hibernate.xml");,这个可以自己在resources下面定义文件名是什么
//        Configuration configuration = new Configuration().configure();
//        System.out.println("configuration = " + configuration);


        //创建Configuration,即配置类对象 默认的是去读hibernate.cfg.xml,
        // 不然你就在下面一行最后面这样写:.configure("hibernate.xml");,这个可以自己在resources下面定义文件名是什么
        Configuration configuration = new Configuration().configure();
        //获取SessionFactory
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //获取Session
        Session session = sessionFactory.openSession();

        //向people表中添加数据
        People people = new People();
        people.setName("张三");
        people.setMoney(1000.0);
        session.save(people);
        //提交事务
        session.beginTransaction().commit();
        //关闭session
        session.close();
    }
}

6、pom.xml 中需要配置 resource

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

7、常见的Hibernate 配置⽂件 属性

########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.southwind.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>

schema:数据库 schema 的名称
catalog:数据库 catalog 的名称
default-cascade:默认的级联关系,默认为 none
default-access:Hibernate ⽤来访问属性的策略
default-lazy:指定了未明确注明 lazy 属性的 Java 属性和集合类,Hibernate 会采⽤什么样的加载
⻛格,默认为 true
auto-import:指定我们是否可以在查询语句中使⽤⾮全限定类名,默认为 true,如果项⽬中有两
个同名的持久化类,最好在这两个类的对应映射⽂件中国配置为 false

######class 属性
name:实体类名
table:数据表名
schema:数据库 schema 的名称,会覆盖 hibernate-mapping 的 schema
catalog:数据库 catalog 的名称,会覆盖 hibernate-mapping 的 catalog
proxy:指定⼀个接⼝,在延迟加载时作为代理使⽤
dynamic-update:动态更新
dynamic-insert:动态添加

######id 属性
name:实体类属性名
type:实体类属性数据类型
此处可以设置两种类型的数据:Java 数据类型或者 Hibernate 映射类型。
实体类的属性数据类型必须与数据表对应的字段数据类型⼀致:
int 对应 int,String 对应 varchar
如何进⾏映射?
Java 数据类型映射到 Hibernate 映射类型,再由 Hibernate 映射类型映射到 SQL 数据类型
Java ---》Hibernate ---〉SQL
column:数据表的主键字段名
<class name="com.southwind.entity.People" table="people" dynamic-insert="true"
dynamic-update="true" where="id = 6">

######generator:主键⽣成策略
1、hilo 算法
2、increment:Hibernate ⾃增
3、identity:数据库⾃增
4、native:本地策略,根据底层数据库⾃动选择主键的⽣成策略
5、uuid.hex 算法
6、select 算法
property 属性
name:实体类的属性名
column:数据表字段名
type:数据类型
update:该字段是否可以修改,默认为 true
insert:该字段是否可以添加,默认为 true
lazy:延迟加载策略

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

91科技

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值