簡體   English   中英

在 Spring Boot 中,如何生成 24 長度的隨機字符串作為實體的主鍵(_id)?

[英]In Spring Boot, how can I generate 24-length random string as a primary key(_id) of the entity?

標題同樣,我試圖生成 24 長度的隨機字符串作為實體的主鍵(_id)。 (例如,“_id”:“6075cb84fb96a8948253d4c1”)因此 GET、PUT、DELETE 方法能夠使用 _id 值。 我嘗試將 UUID 用於 GET 方法,但由於類型的原因它不起作用。 UUID生成的_id是String,但是如下圖所示,_id是Long值,所以我試着把它改成String,但是IDE說需要Long類型。

@GetMapping("/board/view/<objid>")
    public Board getOneBoard(@PathVariable Long _id) {
        Board board = boardRepository.findById(_id).orElseThrow(
                () -> new NullPointerException("Can't find the id.")
        );
        return board;

我能做什么?


(附加代碼)

@NoArgsConstructor 
@Getter
@Entity
public class Board extends Timestamped {

    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid")
    @Column(columnDefinition = "CHAR(32)")
    @Id
    private String _id;

    @Column(nullable = false)
    private int no;

    @Column(nullable = false)
    private String title;

    @Column(nullable = false)
    private String author;

    @Column(nullable = false)
    private String comment;



    public Board(BoardRequestDto requestDto) {
        this._id = requestDto.get_id();
        this.title = requestDto.getTitle();
        this.author = requestDto.getAuthor();
        this.comment = requestDto.getComment();
        this.no = requestDto.getNo();
    }

    public void update(BoardRequestDto requestDto) {
        this._id = requestDto.get_id();
    }
}

請參閱 java 類 UUID 及其方法public static UUID randomUUID() 該類當然也有toString()方法。 這應該可以解決問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM