Hibernate(5)什么是Hibernate的配置文件?

Hibernate的配置文件是用于定义Hibernate的各种配置参数的文件,包括数据库连接信息、Hibernate属性、映射资源、缓存配置等。Hibernate主要使用两种配置文件:

  1. hibernate.cfg.xml:XML格式的配置文件。
  2. hibernate.properties:属性格式的配置文件。

1. hibernate.cfg.xml 配置文件

hibernate.cfg.xml 是一个XML格式的配置文件,用于定义Hibernate的各种配置参数,包括数据库连接信息、Hibernate属性配置、映射资源等。它是Hibernate配置中最常用的文件。

主要功能:

  • 配置数据库连接属性。
  • 配置Hibernate相关属性(如方言、缓存、日志等)。
  • 配置实体类的映射信息。

示例:

以下是一个详细的hibernate.cfg.xml文件示例:

xml 复制代码
<!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="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database</property>
        <property name="hibernate.connection.username">your_username</property>
        <property name="hibernate.connection.password">your_password</property>

        <!-- Hibernate 属性配置 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- 二级缓存配置 -->
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

        <!-- 查询缓存配置 -->
        <property name="hibernate.cache.use_query_cache">true</property>

        <!-- 连接池配置 -->
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>

        <!-- 映射类配置 -->
        <mapping class="com.example.domain.Student"/>
        <mapping class="com.example.domain.Course"/>

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

详细说明:

  • 数据库连接配置:定义了如何连接数据库,包括数据库驱动类、URL、用户名和密码。
  • Hibernate属性配置:配置Hibernate的行为,包括SQL方言、是否显示SQL、SQL格式化选项等。
  • 二级缓存配置:启用二级缓存并指定缓存的实现。
  • 查询缓存配置:启用查询缓存。
  • 连接池配置:配置连接池的行为,如最小连接数、最大连接数、超时时间等。
  • 映射类配置:指定Hibernate需要管理的实体类。

2. hibernate.properties 配置文件

hibernate.properties 是一个属性文件格式的配置文件,用于定义Hibernate的各种配置参数。它的内容相对简单直接,但不如XML格式的配置文件结构化和可读性强。

示例:

以下是一个详细的hibernate.properties文件示例:

properties 复制代码
# 数据库连接配置
hibernate.connection.driver_class = com.mysql.cj.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost:3306/your_database
hibernate.connection.username = your_username
hibernate.connection.password = your_password

# Hibernate 属性配置
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update

# 二级缓存配置
hibernate.cache.use_second_level_cache = true
hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory

# 查询缓存配置
hibernate.cache.use_query_cache = true

# 连接池配置
hibernate.c3p0.min_size = 5
hibernate.c3p0.max_size = 20
hibernate.c3p0.timeout = 300
hibernate.c3p0.max_statements = 50
hibernate.c3p0.idle_test_period = 3000

使用示例

结合上述配置文件,我们可以用以下代码进行Hibernate的初始化和使用:

Java代码示例:

java 复制代码
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static SessionFactory sessionFactory;

    static {
        try {
            // 创建SessionFactory
            sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

public class HibernateExample {
    public static void main(String[] args) {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();

        // 创建并保存学生对象
        Student student = new Student("John Doe", 20);
        session.save(student);

        transaction.commit();

        // 读取学生对象
        transaction = session.beginTransaction();
        Student retrievedStudent = session.get(Student.class, student.getId());
        System.out.println("Retrieved Student: " + retrievedStudent.getName() + ", Age: " + retrievedStudent.getAge());
        transaction.commit();

        // 更新学生对象
        transaction = session.beginTransaction();
        retrievedStudent.setAge(21);
        session.update(retrievedStudent);
        transaction.commit();

        // 删除学生对象
        transaction = session.beginTransaction();
        session.delete(retrievedStudent);
        transaction.commit();

        session.close();
        sessionFactory.close();
    }
}

详细解释

  1. 持久化类定义 :持久化类Student使用了@Entity注解表示这是一个持久化实体类,@Id@GeneratedValue注解用于定义主键和主键生成策略。

  2. hibernate.cfg.xml 配置 :在配置文件中,通过<mapping class="com.example.domain.Student"/>Student类映射到数据库表。

  3. Hibernate操作

    • 创建SessionFactory :通过Configuration类读取hibernate.cfg.xml文件创建SessionFactory
    • 获取Session :通过SessionFactory获取Session对象。
    • 启动事务 :通过Session对象启动事务。
    • CRUD操作
      • 创建并保存 :使用session.save()方法保存一个新的Student对象。
      • 读取 :使用session.get()方法根据主键读取Student对象。
      • 更新 :修改对象的属性值并使用session.update()方法进行更新。
      • 删除 :使用session.delete()方法删除对象。
    • 提交事务 :通过transaction.commit()方法提交事务。

通过这种方式,Hibernate可以将Java对象持久化到数据库中,处理对象的CRUD操作,实现对象与数据库表之间的映射和管理。

相关推荐
子兮曰18 小时前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰18 小时前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
爱勇宝18 小时前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
胡写代码19 小时前
别再前后端各写一套表单校验了
java·后端
大勇前进19 小时前
原生 PHP 还是 Laravel?小项目到底要不要上框架
后端
yuzhi_liu19 小时前
我用 LangGraph4j 实现 Multi-Agent Supervisor
后端
alsmile20 小时前
Node-RED 之外,国产规则引擎的新方案:基于标准语法,Go 先行实现
后端·开源·go
大白8020 小时前
PHP 内存溢出排查思路:看懂报错日志,精准定位问题
后端
二月龙20 小时前
PHP 接口返回统一响应封装,让前后端对接更省心
后端
盖伦发发21 小时前
软件工程SOLID 五大设计原则
后端·软件工程