Hibernate not respecting MySQL auto_increment primary key field

前端 未结 5 2026
攒了一身酷
攒了一身酷 2020-12-15 18:56

I am trying to learn how Hibernate works, and I am running into an almost unacceptable learning curve. I can\'t see how to get Hibernate to respect the auto_increment policy

相关标签:
5条回答
  • 2020-12-15 19:13

    I use the following with auto_increment, works perfectly:

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "db_id", unique = true, nullable = false)
    public Long getDbId() {
        return this.dbId;
    }
    
    public void setDbId(Long dbId) {
        this.dbId = dbId;
    }
    
    0 讨论(0)
  • 2020-12-15 19:15

    I wrote this in a comment under the accepted answer, but those aren't shown by default so I'll re-post it as an answer.

    I was using a hibernate.cfg.xml file off some dude's web site, and it had this:

    <property name="hibernate.hbm2ddl.auto">create</property>
    

    This made the system to re-create my table each time I ran my app. Commenting it out solved the problem.

    The other two answers about the various ways to create IDs are correct. My original problem's symptom seemed to do with ID generation, but the actual cause was misconfiguration.

    0 讨论(0)
  • 2020-12-15 19:15

    You might wish to have a look at: http://hibernatepojoge.sourceforge.net/

    It claims to create a fully working application (spring, hibernate, junit tests, etc) just by pointing it to a DB.

    0 讨论(0)
  • 2020-12-15 19:21

    I think GenerationType.AUTO is right as is <id ...><generator class="native" /></id>

    Picks an appropriate strategy for the particular database.

    http://www.hibernate.org/hib_docs/ejb3-api/javax/persistence/GenerationType.html

    http://www.hibernate.org/hib_docs/reference/en/html/mapping.html

    0 讨论(0)
  • 2020-12-15 19:31

    I believe you want GenerationType.IDENTITY. MySql does not use a table or sequence for generating the Id value.

    0 讨论(0)
提交回复
热议问题