Java/Java
Java 현재 시간 + 랜덤 문자로 고유값 만들기 - with apache commons library (Java Random String)
ysk(0soo)
2023. 1. 28. 21:12
Java 현재 시간 + 랜덤 문자로 고유값 만들기 - with apache commons library (Java Random String)
Apache Commons의 RandomStringUtils 클래스를 이용하여 랜덤 문자열을 만들 수 있다.
RandomStringUtils 을 사용하기 위해서는 commons-lang3이 필요하다.
build.gradle 에 아래 항목을 추가한다.
implementation 'org.apache.commons:commons-lang3:3.0'
import org.apache.commons.lang3.RandomStringUtils;
RandomStringUtils.randomAlphabetic(4);
메서드 인자로 생성할 random String의 length를 넘겨주면 된다.
Custom JPA Id Generator
이를 응용한 현재 시간 + 랜덤 문자로 고유한 Id 값을 만들어 낼 수 있다.
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.apache.commons.lang3.RandomStringUtils;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
public class OrderIdGenerator implements IdentifierGenerator {
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
String currentDateTime = LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
String randomId = RandomStringUtils.randomAlphabetic(4);
return currentDateTime + "-ysk-" + randomId;
}
}