简体   繁体   中英

How to auto-increment database id with uniqe product code and then reset it to 1 when change mont in spring boot?

I am currently working with java spring boot. I am using JPA Repository and postgresql as database

My business owner want me to create id of transaction that contain

PRODUCT_CODE-YEAR-MONTH-INCREMENT_NUMBER
  • increment number contain 8 length number

Example: 0000001, 0000011, 0000201

example : 48-2022-04-0000001
48-2022-04-0000001
48-2022-04-0000002
48-2022-04-0000003
-----> 48-2022-04-0000203

The increment number will be reset to be 0000001 when next month.

Will be:

48-2022-05-0000001

What the best way to do this?

Also if there is any query to select last data on given month and year?

Please help me, I just want to say thank you in advance

Multiple sequences, one per year-month

You don't have one sequence. You have many sequences, one for each month.

Use Postgres commandCREATE SEQUENCE to create a sequence named for each month. I suggest using a sequence name that includes the year-month in standard ISO 8601 format, YYYY-MM.

In Java, use the YearMonth to represent a particular month.

You said:

the increment number will be reset to be 0000001 when next month

No, don't think in terms of resetting. For one thing, there may be exceptional circumstances where you need to create transactions for previous or future months. Resetting would preclude that.

So keep multiple sequences, one per month.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM