简体   繁体   English

休眠中的复合键

[英]Composite Key in Hibernate

Java Persistence with Hibernate shows how to create a composite key: Java Persistence with Hibernate显示了如何创建复合键:

@Entity
@Table(name = "CATEGORIZED_ITEM")
  public class CategorizedItem {

  @Embeddable
  public static class Id implements Serializable {

      @Column(name = "CATEGORY_ID")
      private Long categoryId;

      @Column(name = "ITEM_ID")
      private Long itemId;

      public Id() {}
      public Id(Long categoryId, Long itemId) {
          this.categoryId = categoryId;
          this.itemId = itemId;
      }

      public boolean equals(Object o) {
          if (o != null && o instanceof Id) {
              Id that = (Id)o;
              return this.categoryId.equals(that.categoryId) &&
                  this.itemId.equals(that.itemId);
          } else {
              return false;
          }
      }
      public int hashCode() {
          return categoryId.hashCode() + itemId.hashCode();
      }
  }

@EmbeddedId
private Id id = new Id();

@Column(name = "ADDED_BY_USER")
private String username;

@Column(name = "ADDED_ON")
private Date dateAdded = new Date();

Is the approach of making the Id static common when making a composite key? 制作复合键时,使Id 静态化是否通用? If so, why? 如果是这样,为什么?

Why is it necessary to instantiate Id in CategorizedItem ? 为什么必须在CategorizedItem实例化Id

private Id id = new Id();

There are actually two ways you can specify composite keys, one being @EmbeddedId and the other being an ID class: @IdClass . 实际上,您可以通过两种方式指定组合键,一种是@EmbeddedId ,另一种是ID类: @IdClass This is a pretty good tutorial showing you the options and providing suggestions on how to work on both styles of composite key specifier: http://www.objectdb.com/java/jpa/entity/id 这是一个很好的教程,向您展示了这些选项,并提供了有关如何使用两种组合键说明符样式的建议: http : //www.objectdb.com/java/jpa/entity/id

I haven't personally seen the primary key class be embedded inside the class using that key, but if the key class is not required to be used anywhere else, than it makes sense. 我个人还没有看到使用该键将主键类嵌入到该类中,但是如果不需要在其他任何地方使用该键类,那将是有意义的。 A public static nested class is basically the same as a root level class, it just shows the intent that the class has a tight association with its enclosing class. 公共静态嵌套类与根级别类基本相同,仅表明该类与其封闭类有紧密的联系。

As for creating an instance of the class, I think most examples do it via the constructor. 至于创建类的实例,我认为大多数示例都是通过构造函数来完成的。 You must obviously provide values for the primary key components before trying to persist the entity to the database. 显然,在尝试将实体持久保存到数据库之前,必须为主键组件提供值。 Here's a typical example of that: http://www.java2s.com/Tutorial/Java/0355__JPA/EmbeddedCompoundPrimaryKey.htm 这是一个典型的示例: http : //www.java2s.com/Tutorial/Java/0355__JPA/EmbeddedCompoundPrimaryKey.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM