SoFunction
Updated on 2025-04-13

Several ways to generate a unique order number in Java

Preface

Order numbers have the function of unique identifiers. The following will demonstrate the self-increase, random and combination methods to generate efficient, safe and unique order numbers to meet business needs and avoid potential problems.

Self-increasing

Common self-increasing:Pure numbers increaseTime + number increaseDatabase primary key id is increased

Pure numbers increase

Requirement: Generate an order number with 8-digit self-incremented numbers, and add 0 if it is less than 8-digit prefix.

Implementation: Use redis's incr function to complete this requirement.

@RestController
@RequestMapping("/testOrderCode")
public class TestOrderCodeController {
    @Resource
    private RedisTemplate<String, Integer> redisTemplate;
    private static final String TEST_ORDER_CODE_KEY = "test_order_code_key";

    @GetMapping("/test")
    public String test() {
        //Use incr to get the self-incremented order number        Long increment = ().increment(TEST_ORDER_CODE_KEY);
        //Put the prefix of less than 8 digits of the order number, "%08d", %0 means the prefix supplement 0, 8 means the supplement 8 digits, d means the number type        String oderCode = ("%08d", increment);
        return oderCode;
    }
}
Output result:00000001

Time + number increase

Requirements: Use the year, month, day (yyMMdd) as the prefix of the order number, and the last four digits use the day order number to increase by itself.

Implementation: Get the time string in yyMMdd format, then use the string as the key of redis, and set the expiration time of one day for the key. The last four digits are automatically incremented using the incr function of redis.

@RestController
@RequestMapping("/testOrderCode")
public class TestOrderCodeController {
    @Resource
    private RedisTemplate<String, Integer> redisTemplate;
    private static final String TEST_ORDER_CODE_KEY = "test_order_code_key";

    @GetMapping("/test")
    public String test() {
        // Define date format        DateTimeFormatter formatter = ("yyMMdd");
        //Get the time string in yyMMdd format based on the current time        String format = ().format(formatter);
        //Judge whether there is a key. If there is no, set the expiration time of 1 day        if (((format))) {
            (format, 1, );
        }
        //Use incr to get the self-incremented order number        Long increment = ().increment(format);
        //Put the prefix of less than 4 digits of the order number, "%04d", %0 means the prefix supplement 0, 4 means the supplement 4 digits, d means the number type        String oderCode = ("%04d", increment);
        return format + oderCode;
    }
}
Output result:2412260001

Database primary key id is increased

Requirement: Generate an order number with 8-digit self-incremented numbers, and add 0 if it is less than 8-digit prefix.

Implementation: Use the database to auto-increment primary key to achieve this requirement. First save the order to the database, take the order id, and then update the id prefix to the database after adding 0.

@RestController
@RequestMapping("/testOrderCode")
public class TestOrderCodeController {
    @Resource
    private OrdersMapper orderMapper;

    @GetMapping("/test")
    public String test() {
        //Save the order and get the id        OrdersDO ordersDO = new OrdersDO();
        (ordersDO);
        Long id = ();
        //Put the prefix of less than 8 digits of the order number, "%08d", %0 means the prefix supplement 0, 8 means the supplement 8 digits, d means the number type        String oderCode = ("%08d", id);
        //Update the order number        ((oderCode));
        return oderCode;
    }
}
Output result:00000001

random

Random common ones are:Random numberUUIDDistributed global unique id (snowflake algorithm)

Random number

Requirements: Generate a random order number.

Implementation: Use Random to generate random numbers.

import ;

@RestController
@RequestMapping("/testOrderCode")
public class TestOrderCodeController {
    @Resource
    private OrdersMapper orderMapper;

    @GetMapping("/test")
    public String test() {
        // Define date format        DateTimeFormatter formatter = ("yyMMdd");
        //Get the time string in yyMMdd format based on the current time        String format = ().format(formatter);
        //Generate random 8-digit numbers        String random = (8);
        //Time + random number to form the order number        String oderCode = format + random;
        //Judge whether the generated order number exists in the database. If it exists, continue to randomly generate the order number.        while ((().eq(OrdersDO::getOrderCode, oderCode)) > 0){
            oderCode = format + (8);
        }
        return oderCode;
    }
}
Output result:24122683230048

UUID

Requirements: Generate a random order number.

Implementation: Use UUID to implement this requirement.

import ;

@RestController
@RequestMapping("/testOrderCode")
public class TestOrderCodeController {

    @GetMapping("/test")
    public String test() {
        // Generate a UUID        UUID uuid = ();
        // Convert UUID to string and remove delimiter        String oderCode = ().replace("-", "");
        return oderCode;
    }
}
Output result:8a45cd3458b640789ed3c9ef223d090b

Distributed global unique id (snowflake algorithm)

Requirements: Generate a random order number.

Implementation: Use a distributed global unique id (snowflake algorithm) to implement this requirement.

import ;

@RestController
@RequestMapping("/testOrderCode")
public class TestOrderCodeController {

    @GetMapping("/test")
    public String test() {
        // Create a snowflake algorithm ID generator instance, usually you need to specify the terminal ID and data center ID        Snowflake snowflake = new Snowflake(1, 1);
        String oderCode = ();
        return oderCode;
    }
}
Output result:1872140136729415680

Conclusion

This is the end of this article about several ways to generate a unique order number in Java. For more information about generating a unique order number in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!