Hibernate(1)什么是Hibernate?

Hibernate 是一个开源的对象关系映射(ORM)框架,用于简化 Java 应用程序与关系数据库之间的数据持久化。它将 Java 类映射到数据库表,将 Java 对象的属性映射到表中的列,从而实现对象与关系数据库之间的自动映射与转换。Hibernate 以透明、简洁且高效的方式处理持久化数据,极大地减少了开发者的工作量。

核心概念

  • Session: 用于执行 CRUD 操作的接口,是 Hibernate 与数据库之间的交互接口。
  • SessionFactory: 用于创建 Session 对象的工厂。
  • Configuration: 配置对象,用于加载 Hibernate 配置文件和映射文件。
  • Transaction: 表示数据库事务,用于确保数据操作的完整性和一致性。
  • Query: 用于执行 HQL(Hibernate Query Language)或 SQL 查询的接口。

配置

  1. Hibernate Configuration File (hibernate.cfg.xml): 用于配置数据库连接属性和 Hibernate 相关设置。
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>
        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/yourdb</property>
        <property name="hibernate.connection.username">yourusername</property>
        <property name="hibernate.connection.password">yourpassword</property>

        <!-- JDBC connection pool settings -->
        <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>

        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Mapping files -->
        <mapping resource="path/to/yourmappingfile.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
  1. Entity Class: Java 类映射到数据库表。
java 复制代码
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Employee")
public class Employee {
    @Id
    private int id;
    private String name;
    private String department;
    private double salary;

    // Getters and Setters
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
}
  1. DAO (Data Access Object): 数据库操作的实现类。
java 复制代码
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class EmployeeDAO {

    private static SessionFactory factory;

    static {
        // Create the SessionFactory from hibernate.cfg.xml
        try {
            factory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public void addEmployee(Employee employee) {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.save(employee);
            tx.commit();
        } catch (Exception e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    public Employee getEmployee(int id) {
        Session session = factory.openSession();
        Employee employee = null;
        try {
            employee = session.get(Employee.class, id);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
        return employee;
    }

    public void updateEmployee(Employee employee) {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.update(employee);
            tx.commit();
        } catch (Exception e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    public void deleteEmployee(int id) {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Employee employee = session.get(Employee.class, id);
            if (employee != null) {
                session.delete(employee);
                tx.commit();
            }
        } catch (Exception e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}
  1. Main Class: 测试 DAO 操作。
java 复制代码
public class HibernateExample {
    public static void main(String[] args) {
        EmployeeDAO employeeDAO = new EmployeeDAO();

        // Add Employee
        Employee emp = new Employee();
        emp.setId(1);
        emp.setName("John Doe");
        emp.setDepartment("Engineering");
        emp.setSalary(75000);
        employeeDAO.addEmployee(emp);

        // Get Employee
        Employee retrievedEmp = employeeDAO.getEmployee(1);
        System.out.println("Retrieved Employee: " + retrievedEmp.getName());

        // Update Employee
        retrievedEmp.setSalary(80000);
        employeeDAO.updateEmployee(retrievedEmp);

        // Delete Employee
        employeeDAO.deleteEmployee(1);
    }
}

详细解释

  1. 配置文件hibernate.cfg.xml 配置文件定义了数据库连接属性、JDBC 连接池设置、SQL 方言以及映射文件路径。这个文件是 Hibernate 的核心配置文件,通常放在资源目录下。

  2. 实体类Employee 类使用 @Entity 注解标识为 Hibernate 实体类,@Table 注解定义了该类对应的数据库表名。类的字段映射到表的列,使用 @Id 注解定义主键字段。

  3. DAO 类EmployeeDAO 类包含了基本的 CRUD 操作方法,包括添加、获取、更新和删除员工记录。使用 SessionFactory 创建 Session 对象,使用 Transaction 处理数据库事务,确保数据一致性。

  4. 测试类HibernateExample 类通过 EmployeeDAO 调用 CRUD 操作方法,演示了如何使用 Hibernate 进行数据库操作。

通过这些代码示例,展示了 Hibernate 的基本使用方法,包括配置、实体映射、数据访问和事务管理。Hibernate 提供了一种简洁高效的方式来处理 Java 对象与关系数据库之间的持久化操作。

相关推荐
涡能增压发动积1 天前
同样的代码循环 10次正常 循环 100次就抛异常?自定义 Comparator 的 bug 让我丢尽颜面
后端
Wenweno0o1 天前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
swg3213211 天前
Spring Boot 3.X Oauth2 认证服务与资源服务
java·spring boot·后端
tyung1 天前
一个 main.go 搞定协作白板:你画一笔,全世界都看见
后端·go
gelald1 天前
SpringBoot - 自动配置原理
java·spring boot·后端
殷紫川1 天前
深入拆解 Java 内存模型:从原子性、可见性到有序性,彻底搞懂 happen-before 规则
java·后端
元宝骑士1 天前
FIND_IN_SET使用指南:场景、优缺点与MySQL优化策略
后端·mysql
用户31952370347711 天前
记一次 PostgreSQL WAL 日志撑爆磁盘的排查
后端
nghxni1 天前
LightESB PlatformHttp v3.0.0:JSONPath 订单转换 HTTP 路由实战
后端
武子康1 天前
大数据-263 实时数仓-Canal 增量订阅与消费原理:MySQL Binlog 数据同步实践
大数据·hadoop·后端