使用JPA时,@ Entity和@Table中的name参数之间的区别是什么? [英] What's the difference between the name argument in @Entity and @Table when using JPA?

查看:104
本文介绍了使用JPA时,@ Entity和@Table中的name参数之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JPA2,并且 @Entity @Table 都具有 name 属性,例如.g.:

I'm using JPA2 and both @Entity and @Table have a name attribute, e. g.:

@Entity(name="Foo")
@Table (name="Bar")
class Baz

我应该使用什么,哪些是可选的?

What should I use, which ones are optional?

在我的特定情况下,我有一个 User 类和一个 Group 类,它们有其他要求(据我所知),因为它们是SQL中的保留字.

In my specific case I have a class User and a class Group, which have additional requirements (as far as I understand) because they are reserved words in SQL.

一种可行的解决方案会是什么样子?在编写查询时我将使用哪个名称来引用实体?

How would a working solution look like and with which name would I refer to the entity when writing queries?

更新:我在 Group 中的两个注释中添加了 name ="GROUPS" ,并对 User 进行了相同的操作,但是现在我明白了错误:

Update: I added name="GROUPS" to both annotations in Group and did the same for User, but now I get this error:

Exception Description: The table [USERS] is not present in this descriptor.
Descriptor: RelationalDescriptor(example.Group --> [DatabaseTable(GROUPS)])

和这个错误

Internal Exception: java.sql.SQLException: Table not found in statement [SELECT ID, MAXIMUMROLE, MEMBERSHIPS_ID FROM USERS]

推荐答案

@Table是可选的.将POJO类注释为实体需要@Entity,但是name属性不是必需的.

@Table is optional. @Entity is needed for annotating a POJO class as an entity, but the name attribute is not mandatory.

如果您有课程

 @Entity
 class MyEntity {}

将创建一个名称为" MyEntity "的表,并且实体名称为 MyEntity .您的JPQL查询为:

A table with name "MyEntity" will be created and the Entity name will be MyEntity. Your JPQL query would be:

 select * from MyEntity

在JPQL中,您始终使用实体名称,默认情况下,它是类名称.

In JPQL you always use the Entity name and by default it is the class name.

如果您有课程

 @Entity(name="MyEntityName")
 @Table(name="MyEntityTableName")
 class MyEntity {}

然后创建一个名称为 MyEntityTableName 的表,并且实体名称为 MyEntityName .

then a table with name MyEntityTableName is created and the entity name is MyEntityName.

您的JPQL查询为:

 select * from MyEntityName

这篇关于使用JPA时,@ Entity和@Table中的name参数之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆