java—即使在hibernate中设置了autoincrement,mysql中的表也必须具有auto increment属性吗

gojuced7  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(359)

我得到的错误是id没有默认值

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Setter
@Getter
@Column(name="id")
private Long id;

但是我没有在数据库端设置id的自动递增。是否也必须设置db端。据我所知hibernate可以生成和设置值。
可能是什么原因?提前谢谢。。。

xriantvc

xriantvc1#

在休眠5之前,

@Entity
@Table(name = "post")
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String title;

    public Post() {}

    public Post(String title) {
        this.title = title;
    }
}

但对于hibernate 5,

@Entity
@Table(name = "post")
public class Post {

    @Id
    @GeneratedValue(
        strategy= GenerationType.AUTO, 
        generator="native"
    )
    @GenericGenerator(
        name = "native", 
        strategy = "native"
    )
    private Long id;

    private String title;

    public Post() {}

    public Post(String title) {
        this.title = title;
    }
}

如果不使用genericgenerator,则在执行多个保存请求时,hibernate将执行以下查询:

SELECT next_val as id_val 
FROM hibernate_sequence FOR UPDATE

UPDATE hibernate_sequence 
SET next_val= 2 where next_val=1

SELECT next_val as id_val 
FROM hibernate_sequence FOR UPDATE

UPDATE hibernate_sequence 
SET next_val= 3 where next_val=1

SELECT next_val as id_val 
FROM hibernate_sequence FOR UPDATE

UPDATE hibernate_sequence 
SET next_val= 4 where next_val=3

INSERT INTO post (title, id) 
VALUES ('High-Performance Java Persistence', 1)

INSERT INTO post (title, id) 
VALUES ('High-Performance Java Persistence', 2)

INSERT INTO post (title, id) 
VALUES ('High-Performance Java Persistence', 3)

所以使用

@GenericGenerator(
    name = "native", 
    strategy = "native"
)

将生成以下查询:

INSERT INTO post (title) 
VALUES ('High-Performance Java Persistence')

INSERT INTO post (title) 
VALUES ('High-Performance Java Persistence')

INSERT INTO post (title) 
VALUES ('High-Performance Java Persistence')

因此,执行更少的查询来执行相同的操作,从而获得高性能。。。

qxsslcnc

qxsslcnc2#

如果手动创建模式,则必须将auto increment属性设置为id列。如果您让hibernate生成您的模式,它将自己生成并设置它。

相关问题