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操作,实现对象与数据库表之间的映射和管理。

相关推荐
爬山算法3 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
Moment3 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
Cobyte4 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
程序员侠客行5 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
Honmaple5 小时前
QMD (Quarto Markdown) 搭建与使用指南
后端
PP东5 小时前
Flowable学习(二)——Flowable概念学习
java·后端·学习·flowable
invicinble5 小时前
springboot的核心实现机制原理
java·spring boot·后端
全栈老石6 小时前
Python 异步生存手册:给被 JS async/await 宠坏的全栈工程师
后端·python
space62123276 小时前
在SpringBoot项目中集成MongoDB
spring boot·后端·mongodb
Tony Bai6 小时前
再见,丑陋的 container/heap!Go 泛型堆 heap/v2 提案解析
开发语言·后端·golang