【问题标题】:how to use String as a Primary Key with Annotation in hibernate如何在休眠中使用字符串作为带有注释的主键
【发布时间】:2016-10-04 09:51:01
【问题描述】:

严重:servlet [appServlet] 的 Servlet.service() 在路径 [] 的上下文中抛出异常 [请求处理失败; 嵌套异常是 org.hibernate.id.IdentifierGenerationException: 必须在调用 save() 之前手动分配此类的 ID:com.cihangir.model.Book] 根本原因 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;
    }

    }

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

【问题讨论】:

    标签: mysql hibernate spring-mvc


    【解决方案1】:

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

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

    您可以使用 Java 创建 UUID,如下代码所示:

    UUID.randomUUID().toString();

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多