[ACCEPTED]-Persisting an entity when ID is null and automatically generated in the database-glassfish-4

Accepted answer
Score: 15

Do not use @NotNull constraint on @Id attribute generated 6 using GenerationType.IDENTITY strategy. The problem is @NotNull and other 5 JSR-303 constraints are validated before commit. And 4 the autoincremented identifier isn't available 3 until after the commit completes.

Try this 2 and don't care about ID initialization any 1 more:

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "IDENTIFIER", nullable = false, unique = true)
 private Long identifier;
Score: 0

When I'm using auto increment at the identifier 2 I do like this:

User user = new User();
user.setIdentifier((long) 0);// Assign 0 to ID for MSSQL/MySQL to properly auto_increment the primary key.
user.setUserName("some name");
...

With this Annotation for 1 the id:

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@NotNull
@Column(name = "ID")
private Long id;

More Related questions