简体   繁体   中英

In what ways will Hibernate Handle Primary Key data

I'm starting out using a hibernate framework in my application, and am confused as to how to handle Primary Keys.

Suppose I have an Entity called User, as follows:

@Entity
@Table(name="REGUSER")

public class User {

@Id
private int id;
private String username;
private String password;
private String email;

public User(int id, String username, String password, String email){
    this.id = id;
    this.username = username;
    this.password = password;
    this.email = email;

}

public User(){}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

@Override
public String toString() {
    return "User{" + "id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + '}';
}

}

which registers a user entity to the database. The datatable in which the data is to be persisted:


|Id | Username | Email | Password|


But when attempting to save a User object such as

userA = new User( 0, "NameTest", "MailTest", "PWDTest");

a null cannot be accepted as ID error is thrown.

So where I am confused:

How can it be the user id is passed in a parameter, in the case of the user id being known before persistence, and added to the table?

How can it be to pass nothing as the id, and let hibernate handle primary key assignment and auto incrementation?

Many thanks.

As I know generally we add @GeneratedValue annotation to make the a primary key field automatically assigned by hibernate engine. In that case we don't need to assign an id when creating it.

@Id   
@GeneratedValue(strategy = GenerationType.AUTO)
private int id

public User(String username, String password, String email){
    this.username = username;
    this.password = password;
    this.email = email;
}

User u = User('name', 'pw', 'email@email.com')
session.save(u);
System.out.println(u.id); // the id is automatically assigned after persist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM