Hibernate(46) Hibernate的配置文件如何加载?

在Hibernate中,配置文件通常用于定义数据库连接信息、Hibernate属性和实体类映射等。常见的配置文件包括hibernate.cfg.xmlhibernate.properties。本文将详细介绍如何加载Hibernate的配置文件,并结合代码示例说明。

加载Hibernate配置文件

1. 使用hibernate.cfg.xml加载配置

hibernate.cfg.xml是最常用的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>

        <!-- 映射类 -->
        <mapping class="com.example.domain.Product"/>
        <mapping class="com.example.domain.Category"/>
    </session-factory>
</hibernate-configuration>
加载hibernate.cfg.xml的示例代码
java 复制代码
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // 使用Configuration类加载hibernate.cfg.xml配置文件
            sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

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

在上面的代码中,new Configuration().configure("hibernate.cfg.xml")会自动查找类路径下的hibernate.cfg.xml文件,并加载其中的配置信息。然后使用这些配置信息构建SessionFactory实例。

2. 使用hibernate.properties加载配置

除了hibernate.cfg.xml,Hibernate还支持通过hibernate.properties文件加载配置信息。

示例配置文件 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.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=update
加载hibernate.properties的示例代码
java 复制代码
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // 使用Configuration类加载hibernate.properties配置文件
            Configuration configuration = new Configuration();
            configuration.configure(); // 默认会加载类路径下的hibernate.cfg.xml或hibernate.properties
            sessionFactory = configuration.buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

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

在上面的代码中,configuration.configure()默认会加载类路径下的hibernate.cfg.xmlhibernate.properties文件,可以根据具体需求调整。

配置文件加载的深入解释

  1. Configuration类

    • org.hibernate.cfg.Configuration类是Hibernate用来配置的核心类。它可以从XML文件或Java属性文件加载配置。
    • configure()方法默认查找类路径根目录下的hibernate.cfg.xml文件。如果提供文件名参数,configure("hibernate.properties")则会加载指定文件。
  2. SessionFactory

    • SessionFactory是Hibernate框架中的关键对象,负责创建Session对象。Session对象是单线程的短期对象,用于执行CRUD操作。
    • SessionFactory是线程安全的,可以在应用程序中全局共享,通常在应用启动时创建一次,并在整个应用生命周期中使用。
  3. 异常处理

    • 在静态块中初始化SessionFactory,并捕获任何可能的异常。如果初始化失败,会抛出ExceptionInInitializerError,确保应用及时发现配置问题。

综合示例

以下是一个完整的示例,展示如何配置并加载Hibernate配置文件,创建SessionFactory并执行一些基本操作。

完整示例
java 复制代码
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

// HibernateUtil类
public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

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

// Category类
@Entity
@Table(name = "category")
public class Category {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @OneToMany(mappedBy = "category", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<Product> products = new HashSet<>();

    // Getters 和 Setters
}

// Product类
@Entity
@Table(name = "product")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "price")
    private Double price;

    @ManyToOne
    @JoinColumn(name = "category_id")
    private Category category;

    // Getters 和 Setters
}

// Hibernate测试类
public class HibernateTest {
    public static void main(String[] args) {
        // 获取SessionFactory
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        // 插入示例数据
        insertSampleData(sessionFactory);

        // 关闭SessionFactory
        sessionFactory.close();
    }

    private static void insertSampleData(SessionFactory sessionFactory) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        try {
            Category category = new Category();
            category.setName("Electronics");

            Product product1 = new Product();
            product1.setName("Laptop");
            product1.setPrice(1000.0);

            Product product2 = new Product();
            product2.setName("Smartphone");
            product2.setPrice(500.0);

            category.addProduct(product1);
            category.addProduct(product2);

            session.save(category);

            transaction.commit();
            System.out.println("Inserted sample data");
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

在这个综合示例中,HibernateUtil类负责加载配置文件并创建SessionFactoryCategoryProduct类定义了实体,HibernateTest类则演示了如何使用Hibernate进行数据操作。通过这种方式,可以有效地加载和使用Hibernate的配置文件进行数据库操作。

相关推荐
风景的人生2 小时前
springboot项目用maven插件打包时候报错
java·spring boot·maven
二哈喇子!2 小时前
基于SSM框架的网上商城购物系统的设计与实现(开源项目——实现CRUD功能整体流程超详细)
java·spring·mybatis·ssm
容沁风2 小时前
pycharm启动报错incompatible with Text-specific LCD
java·pycharm
馨谙2 小时前
面试题----用户,组,su,su-,sudo,sudo-,nologin shell
java·前端·数据库
青w韵2 小时前
SpringBoot3.x 升级到 SpringBoot 4.x,JDK17升级到JDK21
java·后端·spring
vx_bisheyuange2 小时前
基于SpringBoot的经方药食服务平台
java·spring boot·后端·毕业设计
哈哈老师啊2 小时前
Springboot企业办公信息化管理系统6z1v1(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
永远是我的最爱2 小时前
基于ASP.NET的图书管理系统的设计与实现
前端·后端·sql·visual studio
惊讶的猫2 小时前
nia500总结
java·spring·mybatis