Hibernate(21)Hibernate的映射文件是什么?

Hibernate的映射文件(Mapping File)是用来定义Java类如何映射到数据库表的XML文件。尽管注解方式越来越流行,但映射文件仍然是配置Hibernate映射关系的重要方式之一。在映射文件中,你可以详细配置类与表、属性与列之间的映射关系,并定义一些特定的行为,如主键生成策略、关联关系等。

映射文件基本结构

映射文件的基本结构如下:

xml 复制代码
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.example.domain.EntityName" table="table_name">
        <id name="id" column="column_name">
            <generator class="generation_strategy"/>
        </id>
        <property name="property_name" column="column_name"/>
        <!-- 其他属性或关联关系的映射 -->
    </class>
</hibernate-mapping>

示例代码

下面是一个完整的示例,包括数据库配置、实体类、映射文件和使用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 resource="com/example/domain/Person.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

实体类 Person

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

public class Person {
    private Long id;
    private String name;
    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;
    }
}

映射文件 Person.hbm.xml

xml 复制代码
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.example.domain.Person" table="person">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name" column="name"/>
        <property name="age" column="age"/>
    </class>
</hibernate-mapping>

使用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 resource="com/example/domain/Person.hbm.xml"/>
  2. 实体类 Person:定义实体类及其属性。

    java 复制代码
    public class Person {
        // 属性和方法
    }
  3. 映射文件 Person.hbm.xml:定义实体类与数据库表及其列的映射关系。

    xml 复制代码
    <class name="com.example.domain.Person" table="person">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="name" column="name"/>
        <property name="age" column="age"/>
    </class>
  4. HibernateUtil类:创建并管理SessionFactory。

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

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

总结

Hibernate的映射文件提供了一种配置Java类与数据库表映射关系的方式。通过配置映射文件,可以灵活地定义类与表、属性与列之间的关系,并指定主键生成策略、关联关系等。在配置映射文件之后,可以利用Hibernate的Session进行CRUD操作,实现对数据库的访问和操作。

相关推荐
while(1){yan}1 天前
Spring事务
java·数据库·spring boot·后端·java-ee·mybatis
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧1 天前
《苍穹外卖》- day01 开发环境搭建
spring boot·后端·spring·maven·intellij-idea·mybatis
_OP_CHEN1 天前
【Linux系统编程】(二十)揭秘 Linux 文件描述符:从底层原理到实战应用,一篇吃透 fd 本质!
linux·后端·操作系统·c/c++·重定向·文件描述符·linux文件
老神在在0011 天前
Token身份验证完整流程
java·前端·后端·学习·java-ee
源码获取_wx:Fegn08951 天前
计算机毕业设计|基于springboot + vue景区管理系统(源码+数据库+文档)
java·vue.js·spring boot·后端·课程设计
星辰徐哥1 天前
Rust函数与流程控制——构建逻辑清晰的系统级程序
开发语言·后端·rust
源代码•宸1 天前
Leetcode—404. 左叶子之和【简单】
经验分享·后端·算法·leetcode·职场和发展·golang·dfs
你这个代码我看不懂1 天前
Spring Boot拦截Http请求设置请求头
spring boot·后端·http
TechPioneer_lp1 天前
小红书后端实习一面|1小时高强度技术追问实录
java·后端·面试·个人开发