Mapping Entity Class Names to SQL Table Names with JPA – 用JPA将实体类名称映射到SQL表名称

最后修改: 2019年 7月 31日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this short tutorial, we’ll learn how to set SQL table names using JPA.

在这个简短的教程中,我们将学习如何使用JPA设置SQL表名。

We’ll cover how JPA generates the default names and how to provide custom ones.

我们将介绍JPA如何生成默认的名字以及如何提供自定义的名字。

2. Default Table Names

2.默认的表名

The JPA default table name generation is specific to its implementation.

JPA默认表名的生成是针对其实现的。

For instance, in Hibernate the default table name is the name of the class with the first letter capitalized. It’s determined through the ImplicitNamingStrategy contract.

例如,在Hibernate中,默认的表名是类的名称,第一个字母大写。它是通过ImplicitNamingStrategy契约确定的。

But we can change this behavior by implementing a PhysicalNamingStrategy interface.

但是我们可以通过实现PhysicalNamingStrategy接口来改变这种行为。

3. Using @Table

3.使用@Table

The easiest way to set a custom SQL table name is to annotate the entity with @javax.persistence.Table and define its name parameter:

设置自定义SQL表名的最简单方法是用@javax.persistence.Table来注释实体,并定义其名称参数。

@Entity
@Table(name = "ARTICLES")
public class Article {
    // ...
}

We can also store the table name in a static final variable:

我们也可以将表名存储在一个静态的最终变量中。

@Entity
@Table(name = Article.TABLE_NAME)
public class Article {
    public static final String TABLE_NAME= "ARTICLES";
    // ...
}

4. Overwriting the Table Name in JPQL Queries

4.在JPQL查询中覆盖表名

By default in JPQL queries, we use the entity class name:

在JPQL查询中,我们默认使用实体类的名称。

select * from Article

But we can change it by defining the name parameter in the @javax.persistence.Entity annotation:

但是我们可以通过在@javax.persistence.Entity注解中定义名称参数来改变它。

@Entity(name = "MyArticle")

Then we’d change our JPQL query to:

然后我们将我们的JPQL查询改成。

select * from MyArticle

5. Conclusion

5.总结

In this article, we’ve learned how JPA generates default table names and how to set SQL table names using JPA.

在这篇文章中,我们已经了解了JPA如何生成默认的表名,以及如何使用JPA设置SQL表名。

As always all source code is available over on GitHub.

像往常一样,所有的源代码都可以在GitHub上找到