如何使用Hibernate映射文件将Java类映射到数据库表

2023-05-15 14:52:42 浏览数 (1)

如何使用Hibernate映射文件将Java类映射到数据库表:

Java类:

代码语言:javascript复制
package com.example.model;

public class Employee {
    private int id;
    private String firstName;
    private String lastName;
    private Department department;

    // Getters and setters
}

public class Department {
    private int id;
    private String name;

    // Getters and setters
}

Hibernate映射文件:

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.example.model">
    <class name="Employee" table="employees">
        <id name="id" column="employee_id">
            <generator class="increment"/>
        </id>
        <property name="firstName" column="first_name"/>
        <property name="lastName" column="last_name"/>
        <many-to-one name="department" class="Department" column="department_id"/>
    </class>
    <class name="Department" table="departments">
        <id name="id" column="department_id">
            <generator class="increment"/>
        </id>
        <property name="name" column="department_name"/>
    </class>
</hibernate-mapping>

上述示例中,<class>元素定义了Employee类和Department类与数据库表的映射关系,<id>元素定义了主键字段的映射,<property>元素定义了普通字段的映射,<many-to-one>元素定义了多对一关系的映射。

0 人点赞