Reputation: 3584
I am using an @Entity
with a CrudRepository
to create an entry in my MySQL database, and I was wondering at what point the @GeneratedValue(strategy = GenerationType.AUTO) execute and generate the auto increment value?
@Entity
@Table(name = "all_contacts")
public class Contact {
//Ideally this would be set as foreign key to application's user schema
private long userId;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column( name="contactid")
private long contactId;
@NotNull
private String name;
//getters and setters
}
//
public interface ContactRepository extends CrudRepository<Contact, Long> { }
I ask because I want to access the value of the contactId
through its getter, but do I have to wait until the ContactRepository.save()
is called?
Upvotes: 0
Views: 1029
Reputation: 483
We get the generated value once SQL insert statement is executed. We can't know the value is being assinged before save(). GenerationType.AUTO number generator generates automatic object IDs for entity objects and this generated numeric value is used for primary key field.
@Entity
public class Entity {
@Id @GeneratedValue(strategy=GenerationType.AUTO) int id;
}
Upvotes: 0
Reputation: 2323
We can't know the new assigned id of that entity prior to executing the SQL INSERT statement.
So, yes you need to ContactRepository.save()
or any command that trigger SQL INSERT statement before can get that id. But save is better because it is guaranteed that it will always return ID.
Upvotes: 1