How does the JPA @SequenceGenerator annotation work

前端 未结 5 1213
轮回少年
轮回少年 2020-11-27 03:43

I am learning JPA and have confusion in the @SequenceGenerator annotation.

To my understanding, it automatically assigns a value to the numeric identity

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 04:28

    I have MySQL schema with autogen values. I use strategy=GenerationType.IDENTITY tag and seems to work fine in MySQL I guess it should work most db engines as well.

    CREATE TABLE user (
        id bigint NOT NULL auto_increment,
        name varchar(64) NOT NULL default '',
        PRIMARY KEY (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    User.java:

    // mark this JavaBean to be JPA scoped class
    @Entity
    @Table(name="user")
    public class User {
        @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
        private long id;    // primary key (autogen surrogate)
    
        @Column(name="name")
        private String name;
    
        public long getId() { return id; }
        public void setId(long id) { this.id = id; }
    
        public String getName() { return name; }
        public void setName(String name) { this.name=name; }
    }
    

提交回复
热议问题