2

I'm pretty new to Spring Data JPA. I want to generate sequence on non-id column, which has prefix but the prefix can be changed on runtime.

for example: if user types 'A' then the data will be 'A00001' ... and it goes on like A00002, A00003. but user could type 'B', 'C'... then the data will be 'B00001', 'B00002'.

Entity:

@Entity
public class UserEntity extends BaseTimeEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(nullable=false, length=20)
    private String role;

    @GeneratorType(type=CustomGenerator.class,when= GenerationTime.INSERT)
    @Column(nullable=false, length=45, unique = true, updatable = false)
    private String loginId;
}

CustomGenerator:

public class CustomGenerator implements ValueGenerator<String> {
    private static final String query = "SELECT CONCAT('A',COALESCE(MAX((SUBSTR(LOGIN_ID,3))),10000)+1) FROM USER WHERE INSTR(LOGIN_ID, 'A')>0";

    @Override
    public String generateValue(Session session, Object o) {

        NativeQuery nativeQuery = session.createSQLQuery(query);
        String loginId = (String) nativeQuery.setFlushMode(COMMIT).uniqueResult();
        return loginId;
    }
}

i figured how to generate sequence on non-id column with some help from this post (How to use a sequence generator for a non ID field?) but still have no idea with how to change prefix dynamically. any help would be appreciated. Thanks in advance.

Best regards,

Eva

godkimchichi
  • 21
  • 1
  • 3

0 Answers0