Hibernate(4)什么是Hibernate的持久化类?

Hibernate的持久化类(Persistent class)是指那些将Java对象映射到数据库表的类。这些类通常是普通的Java对象(POJO,Plain Old Java Object),它们的属性代表数据库表的列,通过Hibernate的映射机制将这些类与数据库表关联起来。

特点和要求

  1. 无参数构造函数:持久化类必须有一个无参数构造函数,Hibernate需要用它来创建对象。
  2. 属性私有:通常,属性是私有的,并通过getter和setter方法访问。
  3. 实现序列化接口 :虽然不是强制性的,但实现java.io.Serializable接口是一个良好的实践,尤其是当你需要将对象在网络中传输或存储在文件中时。

示例:定义一个持久化类

以下是一个详细的持久化类示例,包括类的定义以及如何通过Hibernate对其进行持久化操作。

1. 定义持久化类

java 复制代码
package com.example.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;

@Entity
public class Student implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private int age;

    // 无参数构造函数
    public Student() {}

    // 全参数构造函数
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getters 和 Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

2. hibernate.cfg.xml文件配置

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>
        <!-- 数据库连接配置等省略 -->
        
        <!-- 映射类配置 -->
        <mapping class="com.example.domain.Student"/>
        
    </session-factory>
</hibernate-configuration>

3. 使用Hibernate对持久化类进行操作

以下是如何使用Hibernate对持久化类进行基本的CRUD(创建、读取、更新、删除)操作的示例:

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

public class HibernateExample {
    public static void main(String[] args) {
        // 创建SessionFactory
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        
        // 获取Session
        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
        session.close();
        
        // 关闭SessionFactory
        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操作,实现对象与数据库表之间的映射和管理。

相关推荐
一步一个脚印一个坑17 小时前
用 APM 全链路追踪,29ms 内定位到 Docker 部署的 SSL 配置错误
javascript·后端·监控
aircrushin17 小时前
端到端AI决策架构如何重塑实时协作体验?
前端·javascript·后端
苦瓜小生17 小时前
【黑马点评学习笔记 | 实战篇 】| 6-Redis消息队列
redis·笔记·后端
yhole18 小时前
springboot 修复 Spring Framework 特定条件下目录遍历漏洞(CVE-2024-38819)
spring boot·后端·spring
BingoGo18 小时前
Laravel 13 正式发布 使用 Laravel AI 无缝平滑升级
后端·php
l软件定制开发工作室18 小时前
Spring开发系列教程(34)——打包Spring Boot应用
java·spring boot·后端·spring·springboot
随风,奔跑18 小时前
Spring MVC
java·后端·spring
美团技术团队19 小时前
美团 BI 在指标平台和分析引擎上的探索和实践
后端
JimmtButler19 小时前
我用 Claude Code 给 Claude Code 做了一个 DevTools
后端·claude
Java水解19 小时前
Java 中实现多租户架构:数据隔离策略与实践指南
java·后端