如何在hibernate中使用String作为主键和注释

时间:2016-10-04 09:51:02

标签: mysql hibernate spring-mvc

SEVERE:servlet [appServlet]的Servlet.service()与path []的上下文引发了异常[请求处理失败; 嵌套异常是org.hibernate.id.IdentifierGenerationException: 在根本原因调用save():com.cihangir.model.Book]之前,必须手动分配此类的ID org.hibernate.id.IdentifierGenerationException:在调用save()之前,必须手动分配此类的ID: com.cihangir.model.Book

package com.cihangir.model;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Book {



    @Id
    @Column(name = "ISBN", nullable = false, unique=true)
    @Basic(optional=false)
    private String ISBN;
    private String bookTitle;
    private String category;
    private String author;

    public Book() {

    }

    public Book(String ISBN, String bookTitle, String category, String author) {
        this.ISBN=ISBN;
        this.bookTitle = bookTitle;
        this.category = category;
        this.author = author;
    }

    public String getISBN() {
        return ISBN;
    }

    public void setISBN(String iSBN) {
        ISBN = iSBN;
    }

    public String getBookTitle() {
        return bookTitle;
    }

    public void setBookTitle(String bookTitle) {
        this.bookTitle = bookTitle;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    }

我该如何解决?你能帮助我吗?

1 个答案:

答案 0 :(得分:1)

使用以下String ISBN代码作为主键。

@Id 
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy = "uuid")
@Column(name = "ISBN")
private String ISBN;

OR

您可以从Java创建UUID,如下面的代码:

UUID.randomUUID().toString();