在休眠中为自动增量字段分配键值

时间:2015-02-26 18:41:09

标签: java hibernate

我有一个名为Books的简单pojo:

@Entity
@Table(name = "Books")
public class Books implements Serializable {

    @Id
    @GeneratedValue
    private Integer id;
    @Column(nullable = false)
    private String title;
    @Column(nullable = false)
    private String author;
    @Column(nullable = false)
    private int isbn;
    @Column(nullable = false)
    private double cost;

    public Books() {
    }

    public Books(Integer id, String title, String author) {
        this.id = id;
        this.title = title;
        this.author = author;
    }

    public Books(String title, String author) {
        this.title = title;
        this.author = author;
    }
//getters / setters

现在,这是Main类:

public static void main(String[] args) throws Exception {

    BookService bookService = new BookService();
    Books book1 = new Books(1, "The Brothers Karamazov", "Fyodor Dostoevsky");
    Books book2 = new Books(2, "War and Peace", "Leo Tolstoy");
    Books book3 = new Books(3, "Pride and Prejudice", "Jane Austen");

    bookService.persist(book1);
    bookService.persist(book2);
    bookService.persist(book3);

    System.exit(0);
}

结果为:

enter image description here

如果我重新运行main类,那么结果是:

enter image description here

hibernate.hbm2ddl.auto值为update

我知道,因为我有@GeneratedValue注释,然后我得到了另一个id,但为什么它不显示assign Key Value for auto increment property之类的错误?

我应该删除setter的{​​{1}}方法吗?

1 个答案:

答案 0 :(得分:0)

创建自动增量id时,Hibernate创建一个指向auto_increment值的指针,并获取可用于保存新对象的下一个id,并使用此id保存对象。

例如,

保存第一个对象时,它将auto_increment值设为1,然后使用1保存对象。 保存第二个对象时,它会将auto_increment值设为2,然后使用该id保存对象。

learn more about id generation strategies

如果存在任何基于模式的更改,

hibernate.hbm2ddl.auto只会更新数据库

相关问题