Using sequence in MySQL and Hibernate

好久不见. 提交于 2019-11-29 10:47:18

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?

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