Who is responsible of the auto-incrementation of a primary key between MySQL and Hibernate?

允我心安 提交于 2019-12-22 06:16:28

问题


MySQL

CREATE TABLE `role` (
  `id_role` INT(11) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id_role`)
) AUTO_INCREMENT=1;

Hibernate

@Entity
public class Role {

    private Integer idRole;

    @Column(name = "id_role", precision = 10)
    @GeneratedValue
    @Id
    public Integer getIdRole() {
        return idRole;
    }

    public void setIdRole(Integer idRole) {
        this.idRole = idRole;
    }

}

Given the above background, who is responsible of the auto-incrementation of the id_role column when creating a new role? In other words, does Hibernate set the primary key value before running the create SQL statement, or does it set it to null and let MySQL auto-increments the field while getting back the chosen primary key?


回答1:


To use a MySQL AUTO_INCREMENT column, you are supposed to use an IDENTITY strategy:

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

Which is what you'd get when using AUTO with MySQL:

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

Which is actually equivalent to

@Id @GeneratedValue
private Long id;



回答2:


If you specify GenerationType.IDENTITY , then the database will be in charge assigning the initial identifier. So, using

@GeneratedValue(strategy=GenerationType.IDENTITY)

would leave the DB in-charge.




回答3:


It is definitely the database. Each db dialect has a slightly different way for Hibernate to then query what that newly assigned ID was so it can set it on your entity



来源:https://stackoverflow.com/questions/15390856/who-is-responsible-of-the-auto-incrementation-of-a-primary-key-between-mysql-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!