【问题标题】:Name attribute in @Entity and @Table@Entity 和 @Table 中的名称属性
【发布时间】:2013-09-14 23:21:42
【问题描述】:

我有一个疑问,因为@Entity 和@Table 中都有 name 属性

例如,我可以为 name 属性设置相同的值

@Entity(name = "someThing")
@Table(name = "someThing")

同一个班级也可以有不同的名字

 @Entity(name = "someThing")
 @Table(name = "otherThing")

谁能告诉我这两者之间有什么区别以及为什么我们在两者中具有相同的属性?

【问题讨论】:

  • @Entity 现已弃用。
  • @PhilipRego:虽然 Hibernate 的 \@Entity(即 org.hibernate.annotations.Entity)已被弃用,但 JPA 的 \@Entity(即 javax.persistence.Entity)仍然存在且运行良好。

标签: java hibernate jpa annotations persistence


【解决方案1】:
@Entity(name = "someThing") => this name will be used to name the Entity
@Table(name = "someThing")  => this name will be used to name a table in DB

因此,在第一种情况下,您的表和实体将具有相同的名称,这将允许您在编写 HQL 或 JPQL 时使用与实体相同的名称访问您的表。

在第二种情况下,在编写查询时,您必须使用 @Entity 中给出的名称,而 @Table 中给出的名称将用于在数据库。

因此,在 HQL 中,您的 someThing 将引用数据库中的 otherThing

【讨论】:

    【解决方案2】:

    @Entity(name = "someThing") => 此名称将用于识别域..此名称将仅由 hql 查询识别..即..域对象的名称

    @Table(name = "someThing") => 此名称将用于域对象引用的哪个表..即..表的名称

    【讨论】:

      【解决方案3】:

      @Entity 可用于模型类来表示这是实体或表

      @Table 用于为您的表提供任何特定名称,如果您想提供任何不同的名称

      注意:如果你不使用@Table,那么hibernate认为@Entity是你的默认表名,@Entity必须

      @Entity    
      @Table(name = "emp")     
      public class Employee implements java.io.Serializable    
      {
      
      }
      

      【讨论】:

        【解决方案4】:

        @Table 的 name 属性是实际的表名。 如果您有两个具有相同名称的 @Entity 类并且您需要在运行查询时区分它们,@Entity 的名称很有用。

        【讨论】:

        • 什么时候有两个同名实体?是不是类名相同,但是类在不同包(限定名不同)的时候?
        【解决方案5】:

        这是一个带有一些良好实践技巧的真实示例,因为我只花了 2 个小时试图弄清楚为什么我的 HQL 查询抛出了

        当我在@Entity 注解中使用my_entity 时出现Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: MyEntity is not mapped [SELECT e FROM MyEntity e ... 异常。

        @Entity 名称用于在整个应用程序中引用您的实体,尤其是在 HQL 查询中,@Table 是实际的 DB 表名称,例如:

        @Entity(name = "SomeThing")
        @Table(name = "some_thing")
        public class SomeThing {
            @Id
            private Long id;
        }
        

        ,那么您的 JPA 存储库可能类似于:

            @Repository
            public interface BikeOfferRepository extends JpaRepository<SomeThing, Long> {
            
                /** A contrived example as in reality you'd use built-in 
                    query for this type of select */
                @Query("SELECT o FROM SomeThing WHERE o.id =:id") // <-- Here you use "SomeThing", the entity name in HQL
                SomeThing findAllByBikeOwner(@Param("id") Long id);
            }
        

        顺便说一句,使用类名或驼峰式名称作为实体名称并使用下划线作为表名和列名的小写字母(如我上面的示例)是一个很好的做法。在此处查看有关数据库命名约定的更多信息: https://www.sqlshack.com/learn-sql-naming-conventions/.

        在实际数据库中(或者如果您使用旧式 JDBC 查询),您会使用:

        select * from some_thing where id=xxx;
        

        【讨论】:

          猜你喜欢
          • 2016-06-25
          • 1970-01-01
          • 2011-10-15
          • 1970-01-01
          • 2017-08-31
          • 1970-01-01
          • 1970-01-01
          • 2015-08-07
          相关资源
          最近更新 更多