Hibernate 如何映射列?

How does Hibernate map columns?

我正在通过 Spring 制作 REST api 以从数据库中检索数据。但是我想了解 Hibernate 究竟如何将列映射到 POJO?

数据库中的列名如'FIRST_NAME'、'LAST_NAME'。在 POJO 中,我将 属性 命名为 'firstName' 和 'lastName'。但是,Hibernate 仍然可以正确映射。这是怎么发生的?

通常,我们会使用 @Column 来显式定义映射到 属性 的列名。如果未使用 @Column,它将使用配置的命名策略来确定应将 属性 映射到哪个列。

我猜您正在使用自定义的 PhysicalNamingStrategy,它将小驼峰 属性 映射到 HIGHER_UNDERSCORE 列。

您可以参考 docs 以获取有关命名策略行为的更多信息。


正如您在评论中提到的,您正在使用 spring,我相信您也在使用 spring 引导,默认情况下将物理命名策略配置为 SpringPhysicalNamingStrategydocs) :

By default, Spring Boot configures the physical naming strategy with SpringPhysicalNamingStrategy. This implementation provides the same table structure as Hibernate 4: all dots are replaced by underscores and camel casing is replaced by underscores as well. By default, all table names are generated in lower case, but it is possible to override that flag if your schema requires it.

For example, a TelephoneNumber entity is mapped to the telephone_number table.

我相信你在某个地方创建了一个 hbm 文件(主要是基于 XML 而不是基于注释,因为你没有提供代码)这是在 XML 中编写的文件。这是允许使用 POJO class 映射列的文件。 我们可以定义如下映射文件,它指示 Hibernate 如何将定义的 class 或 classes 映射到数据库表。 (这一般是为了你的理解)

例如:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.nearex.scheduler.dto">
    <class name="SchedulerJobMaster" table="scheduler_job_master">
        <id name="jmId" type="int">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="firstName" type="string">
            <column name="FIRST_NAME"/>
        </property>
        <property name="lastName" type="string">
            <column name="LAST_NAME"/>
        </property>              

    </class>    
</hibernate-mapping>

您可以阅读本教程以获得更好的参考:https://www.tutorialspoint.com/hibernate/hibernate_mapping_files.htm