5

I have a trouble generating id's for new entities, i tried:

@Id
@GeneratedValue
private Long myId;

and

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

but on entityManager.persist i get Table "SEQUENCE" not found In pure hibernate generator class="increment" worked for me just fine.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
bunnyjesse112
  • 747
  • 6
  • 27
  • 44

3 Answers3

15

You could define myId as auto increment / identity column in database and annotate corresponding field entity following way:

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

That works at least with H2 1.3.160 & Hibernate 3.6.8.

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
2

Did you try this..

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
Prashanth
  • 1,388
  • 2
  • 11
  • 26
0

If you like to generate IDs that are shared (and unique) between multiple persisted objects use the @TableGenerator. H2 and many other databases don't have internal support for sequences so @SequenceGenerator doesn't work.

Here's a quick example to have a unique/shared @Id across two objects:

@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;
}
Parham
  • 1
  • 1