【问题标题】:How to annotate id so it's autoincrements without SEQUENCE table?如何注释 id 使其在没有 SEQUENCE 表的情况下自动递增?
【发布时间】:2012-04-12 04:27:42
【问题描述】:

我在为新实体生成 ID 时遇到问题,我尝试过:

@Id
@GeneratedValue
private Long myId;

@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
private Long myId;

但是在entityManager.persist 我得到Table "SEQUENCE" not found 在纯休眠中generator class="increment" 为我工作得很好。

【问题讨论】:

  • H2 数据库。生成器 class="increment" 在纯休眠中工作

标签: hibernate jpa sequence auto-generate


【解决方案1】:

您可以在数据库中将 myId 定义为 自动增量/标识列,并按照以下方式注释相应的字段实体:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long myId;

这至少适用于 H2 1.3.160 和 Hibernate 3.6.8。

【讨论】:

  • 我想强调将数据库列定义为 AUTO_INCREMENT 的重要性。
【解决方案2】:

你试过了吗..

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

【讨论】:

【解决方案3】:

如果您想生成在多个持久对象之间共享(且唯一)的 ID,请使用 @TableGenerator。 H2 和许多其他数据库没有对序列的内部支持,因此 @SequenceGenerator 不起作用。

这是一个跨两个对象拥有唯一/共享@Id 的快速示例:

@Entity
public class Class1 {

  // setting pkColumnValue of TableGenerator is very important ;-)
  @Id
  @TableGenerator(
      name = "guid", 
      initialValue = 0, 
      allocationSize = 10, 
      table = "GUID_SEQ", 
      pkColumnName = "GEN_KEY", 
      valueColumnName = "GEN_VALUE", 
      pkColumnValue = "GUID")
  @GeneratedValue(strategy = GenerationType.TABLE, generator = "guid")
  private long id;
}


@Entity
public class Class2 {

  // use the same pkColumnValue 
  @Id
  @TableGenerator(
      name = "guid", 
      initialValue = 0, 
      allocationSize = 10, 
      table = "GUID_SEQ", 
      pkColumnName = "GEN_KEY", 
      valueColumnName = "GEN_VALUE", 
      pkColumnValue = "GUID")
  @GeneratedValue(strategy = GenerationType.TABLE, generator = "guid")
  private long id;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多