java – JPA,HIBERNATE. How to get the next value from @ tablegenerator

I have an entity class with the following primary key generation strategy

@Id
@Column(name = "id",nullable = false)
@TableGenerator(name = "USERGENERATOR",table = "my_sequences",pkColumnName = "sequence_name",pkColumnValue = "user_id",valueColumnName = "next_value")
@GeneratedValue(strategy = GenerationType.TABLE,generator = "USERGENERATOR")
protected Integer id;

This works until I need to insert new requirements for new rows using native queries Due to the entity inheritance policy (@ inheritance (strategy = inheritancetype. Table_per_class)), the primary key column does not use auto_ increment.

I wonder if there is a way to use the entitymanager to request the next value from the table generator

Solution

I don't think you can access @ tablegenerator through any public API, but it's easy to get the next value using native SQL Just use these two queries:

-- get the current value
select next_value from my_sequences where sequence_name = 'user_id';
-- update value
update my_sequences set next_value = next_value + 1;

If @ tablegenerator gets the next value at the same time, there is a risk of conflict

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>