How to annotate an identifier so that it automatically turns on without a SEQUENCE table?

I have a problem creating id for new objects, 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 hibernation, the generator class="increment" worked just fine for me.

+4
source share
3 answers

You can define myId as an auto-increment / identity column in the database and annotate the corresponding field object as follows:

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

This works with at least H2 1.3.160 and Hibernate 3.6.8.

+13
source

You have tried it.

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

If you like to generate identifiers that are shared (and unique) between multiple stored objects, use @TableGenerator. H2 and many other databases do not have internal sequence support, so @SequenceGenerator does not work.

Here is a quick example to have a unique / shared @Id through 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; } 
0
source

Source: https://habr.com/ru/post/1403920/


All Articles