복붙노트

[SPRING] JPA에서 사용자 정의 ID 생성 방법

SPRING

JPA에서 사용자 정의 ID 생성 방법

JPA에서 사용자 정의 ID를 생성하려면 테이블의 기본 키가되어야합니다. 이 같은 최대 절전 모드를 사용하여 사용자 지정 ID를 만드는 많은 예제가 있습니다. 나는 JPA에서 동일한 구현을 원한다. ID는 STAND0001과 같은 영숫자 여야한다.

감사.

해결법

  1. ==============================

    1.다음과 같이 GenericGenerator를 사용하여이 작업을 수행 할 수 있습니다.

    다음과 같이 GenericGenerator를 사용하여이 작업을 수행 할 수 있습니다.

     @Entity
    public class Client {
    
        @Id
        @GenericGenerator(name = "client_id", strategy = "com.eframe.model.generator.ClientIdGenerator")
        @GeneratedValue(generator = "client_id")  
        @Column(name="client_id")
        private String clientId;
    }
    

    사용자 정의 생성기 클래스 (ID에 접두사를 추가하면 원하는대로 할 수 있습니다).

    public class ClientIdGenerator implements IdentifierGenerator {
    
    @Override
    public Serializable generate(SessionImplementor session, Object object)
            throws HibernateException {
    
        String prefix = "cli";
        Connection connection = session.connection();
    
        try {
            Statement statement=connection.createStatement();
    
            ResultSet rs=statement.executeQuery("select count(client_id) as Id from Client");
    
            if(rs.next())
            {
                int id=rs.getInt(1)+101;
                String generatedId = prefix + new Integer(id).toString();
                return generatedId;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        return null;
    }
    }
    
  2. from https://stackoverflow.com/questions/47259048/how-to-generate-custom-id-in-jpa by cc-by-sa and MIT license