我有一个名为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);
}
结果为:
如果我重新运行main
类,那么结果是:
hibernate.hbm2ddl.auto
值为update
。
我知道,因为我有@GeneratedValue
注释,然后我得到了另一个id
,但为什么它不显示assign Key Value for auto increment property
之类的错误?
我应该删除setter
的{{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
只会更新数据库