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操作,实现对数据库的访问和操作。

相关推荐
pe7er1 天前
如何阅读英文文档
java·前端·后端
pe7er1 天前
IDEA 实用小技巧(自用)
后端
Victor3561 天前
Hibernate(22)Hibernate的注解配置是什么?
后端
喵叔哟1 天前
15.故障排查与调试
后端·docker·容器·服务发现
开心猴爷1 天前
Perfdog 成本变高之后,Windows 上还能怎么做 iOS APP 性能测试
后端
rannn_1111 天前
【Java项目】中北大学Java大作业|电商平台
java·git·后端·课程设计·中北大学
苏三说技术1 天前
日常工作中如何对接第三方系统?
后端
凌览1 天前
0成本、0代码、全球CDN:Vercel + Notion快速搭建个人博客
前端·后端
决战灬1 天前
Hologres高性能写入
后端