字符串作为Spring实体的ID

时间:2018-07-12 10:33:41

标签: java spring spring-data-jpa

我正在尝试创建具有字符串ID的实体:

@Entity
@NoArgsConstructor
@Getter @Setter
public class Account {

    @Id
    private String username;

    private String password;

    public Account(String username, String password) {
        this(username, username + "pass");
    }

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

但是我无法保存此实体:accounts.save(new Account(name, pass)); 错误:org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before calling save():

怎么了?

1 个答案:

答案 0 :(得分:3)

如果要在保存时自动分配ID,则必须用@GeneratedValue(strategy=GenerationType.IDENTITY)注释ID列