简体   繁体   中英

Assign key value for auto increment field in hibernate

I have a simple pojo called Books :

@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

Now, this is Main class:

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);
}

Will result as:

在此输入图像描述

And if i re-run the main class, then the result is:

在此输入图像描述

The hibernate.hbm2ddl.auto value is update .

I know since i have @GeneratedValue annotation, then i got another id , But why it does not displays an error for something like assign Key Value for auto increment property ?

Should i remove setter method of id ?

Hibernate while creating the auto increment id's create a pointer to the auto_increment value and gets the next id that can be used to save a new object and with this id the object is saved.

for example When you save first object it gets auto_increment value as 1, it then uses 1 to save the object. when you save second object it will get the auto_increment value as 2, it then uses this id to save the object.

learn more about id generation strategies

hibernate.hbm2ddl.auto just updates the database if there are any schema based changes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM