Hibernate(22)Hibernate的注解配置是什么?

Hibernate的注解配置是一种通过在Java类和属性上使用注解来定义数据库映射关系的方式,取代了传统的XML映射文件。这种方式使得配置更加直观和简洁,减少了配置文件的维护工作。

使用注解配置Hibernate

配置步骤

  1. 配置Hibernate的核心配置文件 hibernate.cfg.xml
  2. 创建实体类,并使用JPA和Hibernate的注解来定义类和属性的映射。
  3. 使用Hibernate进行CRUD操作

示例代码

下面是一个完整的示例,包括数据库配置、实体类、以及使用Hibernate进行CRUD操作的代码。

配置文件 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.Person"/>
    </session-factory>
</hibernate-configuration>

实体类 Person

使用JPA和Hibernate的注解来配置实体类。

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

import javax.persistence.*;

@Entity
@Table(name = "person")
public class Person {

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

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

    @Column(name = "age")
    private int age;

    public Person() {}

    public Person(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;
    }
}

使用Hibernate进行CRUD操作

HibernateUtil类
java 复制代码
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // 从配置文件创建SessionFactory
            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;
    }
}
CRUD操作类
java 复制代码
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class HibernateCRUDExample {
    public static void main(String[] args) {
        // 获取SessionFactory
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        // 插入数据
        insertPerson(sessionFactory);

        // 查询数据
        queryPerson(sessionFactory);

        // 更新数据
        updatePerson(sessionFactory);

        // 删除数据
        deletePerson(sessionFactory);

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

    private static void insertPerson(SessionFactory sessionFactory) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        try {
            Person person = new Person("John Doe", 30);
            session.save(person);
            transaction.commit();
            System.out.println("Inserted Person: " + person.getName());
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    private static void queryPerson(SessionFactory sessionFactory) {
        Session session = sessionFactory.openSession();
        try {
            Person person = session.get(Person.class, 1L);
            if (person != null) {
                System.out.println("Queried Person: " + person.getName() + ", Age: " + person.getAge());
            } else {
                System.out.println("No Person found with ID 1");
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    private static void updatePerson(SessionFactory sessionFactory) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        try {
            Person person = session.get(Person.class, 1L);
            if (person != null) {
                person.setName("Jane Doe");
                person.setAge(25);
                session.update(person);
                transaction.commit();
                System.out.println("Updated Person: " + person.getName() + ", Age: " + person.getAge());
            } else {
                System.out.println("No Person found with ID 1");
            }
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    private static void deletePerson(SessionFactory sessionFactory) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        try {
            Person person = session.get(Person.class, 1L);
            if (person != null) {
                session.delete(person);
                transaction.commit();
                System.out.println("Deleted Person: " + person.getName());
            } else {
                System.out.println("No Person found with ID 1");
            }
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }
}

详细解释

  1. 配置文件 hibernate.cfg.xml:定义数据库连接信息、Hibernate属性以及实体类映射配置。

    xml 复制代码
    <mapping class="com.example.domain.Person"/>
  2. 实体类 Person:使用JPA和Hibernate的注解定义实体类及其属性的映射。

    • @Entity:指定这是一个持久化实体。
    • @Table(name = "person"):指定表名。
    • @Id:表示主键。
    • @GeneratedValue(strategy = GenerationType.IDENTITY):指定主键生成策略。
    • @Column(name = "name"):指定列名。
  3. HibernateUtil类:创建并管理SessionFactory。

    java 复制代码
    public class HibernateUtil {
        // 创建SessionFactory的代码
    }
  4. CRUD操作类:演示了如何使用Hibernate进行插入、查询、更新和删除操作。

    java 复制代码
    public class HibernateCRUDExample {
        // CRUD操作方法
    }

总结

使用注解配置Hibernate,可以使得配置更加直观和简洁,减少配置文件的维护工作。通过在实体类中使用JPA和Hibernate的注解,可以方便地定义类和属性与数据库表和列之间的映射关系。在配置完成后,可以使用Hibernate的Session进行CRUD操作,实现对数据库的访问和操作。

相关推荐
Victor35612 分钟前
Hibernate(24)Hibernate如何实现乐观锁?
后端
Victor35614 分钟前
Hibernate(23)什么是Hibernate的caching provider?
后端
夕颜1111 小时前
BeeAI 框架—ReActAgent 学习
后端
码事漫谈1 小时前
实验报告:static变量与#include机制的相互作
后端
YanDDDeat1 小时前
Prometheus + Grafana 搭建应用监控体系
java·后端·eureka·grafana·prometheus
hssfscv1 小时前
JavaWeb学习笔记——后端实战1_准备工作
笔记·后端·学习
Loo国昌1 小时前
RAG 第一阶段:前沿技术剖析与环境搭建
人工智能·后端·语言模型·架构
乌日尼乐2 小时前
【Java基础整理】基本数据类型及转换
java·后端
乌日尼乐2 小时前
【Java基础整理】静态static关键字
java·后端
踏浪无痕2 小时前
SQLInsight:一行依赖,自动追踪API背后的每一条SQL
后端·架构·开源