简体   繁体   English

休眠将以何种方式处理主键数据

[英]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: 假设我有一个名为User的实体,如下所示:

@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 | | 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. 由于会引发ID错误,因此不能接受null。

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? 如果在持久化之前已知道用户ID并将其添加到表中,该用户ID如何传递给参数?

How can it be to pass nothing as the id, and let hibernate handle primary key assignment and auto incrementation? 如何不传递任何内容作为id,而让hibernate处理主键分配和自动递增?

Many thanks. 非常感谢。

As I know generally we add @GeneratedValue annotation to make the a primary key field automatically assigned by hibernate engine. 据我所知,通常我们添加@GeneratedValue批注以使休眠引擎自动分配主键字段。 In that case we don't need to assign an id when creating it. 在这种情况下,我们在创建ID时无需分配ID。

@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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