Reputation: 1165
I am storing values like names,password,username,email
in database and i want that an id
a primary column automatically created and it's value start with 1 and automatically increment . I am creating one class user
and it has data member like i write
@Entity
public class User extends Model {
@Id(start)
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Required
@MinLength(value=4)
public String username;
@Required
public String name;
@Required
@MinLength(value=6)
public String password;
@Required
@Email
public String email;
public User(String name,String username,String password,String email)
{
this.name=name;
this.username=username;
this.password=password;
this.email=email;
}
}
i am storing value in database and it is storing value and creating id column in database like this screenshot of database
In this screenshot it is creating random value and storing that value in id
column like 129 141 161 162
but i don't want this value i want that value will start with 1, 2,3
like this.
Please anyone have idea about which annotation i have to use for this that create column automatically and start value with 1? and How to do it ?
Give me some idea.
Upvotes: 0
Views: 718
Reputation: 1652
The thing about GenerationType.AUTO is that the ID that it generates is unique at database level and is never recycled. This means that in table1, your id field may increment from 2 to 6, if id's 3, 4 and 5 exist in other tables.
Try using the generation strategy GenerationType.IDENTITY (or GenerationType.SEQUENCE which has been explained in another answer). The identity generation strategy manages unique id's per type hirarchy, so the id's are essentially sequential per table i.e. 1, 2, 3, 4 etc....
Theres a great tutorial at The ObjectDB Website for more information.
Upvotes: 1
Reputation: 1452
dont know about create column automatically but here is how to fill it automatically:
first create sequence in database SEQUENCE than in entity class:
@Id
@Column(name = "id", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_increment")
@SequenceGenerator(name = "id_increment", sequenceName = "seq_name", allocationSize = 1)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
than when u add record to database column will be fill full with number from sequence +1
and ofc u will not need to set up id field earlier it will be set automatically
Upvotes: 1