简体   繁体   中英

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

Title likewise, I'm trying to generate 24-length random string as a primary key(_id) of the entity. (For example, "_id": "6075cb84fb96a8948253d4c1") So GET, PUT, DELETE method is capable with the _id value. I tried to use UUID for GET method but it didn't work due to the type. _id which is generated by UUID is String, but as it can be seen below, _id is Long value, so I tried to change it to String, but IDE said that type Long is required.

@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;

What can I do?


(additional code)

@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();
    }
}

See java class UUID and its method public static UUID randomUUID() . The class of course has toString() method as well. This should do the trick

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