Using sequence in MySQL and Hibernate

前端 未结 1 654
闹比i
闹比i 2020-12-19 10:15

I\'m working on a project that uses Hibernate and MySQL. I intend to use sequence to generate ID for all tables in database. (It\'s hard to describe my question, so I will s

相关标签:
1条回答
  • 2020-12-19 10:49

    You don't have sequences in Mysql, but you can use the 'TABLE' id generation

    @javax.persistence.TableGenerator(
        name="EMP_GEN",
        table="GENERATOR_TABLE",
        pkColumnName = "key",
        valueColumnName = "hi"
        pkColumnValue="EMP",
        allocationSize=20
    )
    
    @Entity
    public class Klass {
    
        @Id
        @GeneratedValue(strategy = GenerationType.TABLE, generator=EMP_GEN)
        @Column(name = "ID")
        private Long id;
    }
    

    You might need to add the snippet @javax.persistence.TableGenerator [...] in all your entities

    Edit

    Thank you so much. But do we have another way to use that snippet without adding it to each entity? And when creating tables on database, how can I declare the ID primary key column for DBMS to auto-generate the value like that? – napoleonit76

    Unfortunately, I don't know an elegant way to do this :(. In my project, we use the a sequence in several entities, and we need to declare the sequence in each class. One thing you could try (but I don't really like) is to create a super class for all of your entities, and that superclass only contains the ID field and the annotations. I have the feeling that I've seen this in a project, but I'm not 100% sure.

    About telling the DB to use that strategy, I don't think it's really possible. You can try to add a trigger and apply it to each table in the schema. The trigger will fire when you insert a new row in the table, pick a value from the generator table, and add it to the row. I honestly don't know if this might work, and I'm 99% sure that this won't work if you have 2 concurrent sessions creating rows.

    Can you rethink your strategy and use normal auto-increment columns for the ids and put the sequential number in another column of your tables?

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