Kamil Witkowski
Kamil Witkowski

Reputation: 2083

Spring unique ID as integer with excatly 9 digits - not sequence

I am trying to find best practise to generate id of Entity in Spring with following requirements:

I can not use uuid cause it does not follow requirements.

I am using Hibernate currently version 4.3.1 - but probably i could update if needed.

Upvotes: 1

Views: 3851

Answers (2)

Kamil Witkowski
Kamil Witkowski

Reputation: 2083

I resolved the problem this way:

 package com.project.generator;

import ...

public class IdGenerator extends SequenceGenerator
{
    Random r = new Random();
    private Logger log = LoggerFactory.getLogger(IdGenerator.class);
    Session session;

    int attempt = 0;

    public int generate9DigitNumber()
    {
        int aNumber = (int) ((Math.random() * 900000000) + 100000000); 
        return aNumber;
    }

    @Override
    public Serializable generate(SessionImplementor sessionImplementor, Object obj)
    {
        session = (Session) sessionImplementor;
        Integer id = generateRandomIndex();
        return id;
    }

    public Integer generateRandomIndex()
    {
            for (int i = 0; i < 3; i++)
    {
        log.info("attempt: " + i);
        Integer a = generate9DigitNumber();

        log.info("index: " + String.valueOf(a));
        if (session.get(Xyz.class, a) == null)
        {
            log.info("not found this id");
            return a;
        } else
        {
            log.info("found this id");
        }
    }

    for (int i = 100000000; i < 999999999; i++)
    {
        log.info("Is id free: " + i);
        if (session.get(Xyz.class, i) == null)
        {
            log.info("id is free: " + i);
            return i;
        }
    }
        return null;
    }
}

Entity class:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "IdGenerator")
@GenericGenerator(name = "IdGenerator",
    strategy = "com.project.generator.IdGenerator",
    parameters = {
        @Parameter(name = "sequence", value = "xyz_id_sequence")
    })
private Integer id;

Upvotes: 1

AmanSinghal
AmanSinghal

Reputation: 2494

You can use a custom ID generator to generate the ID

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "XyzIdGenerator")
@GenericGenerator(name = "XyzIdGenerator",
    strategy = "com.mycompany.myapp.id.BigIntegerSequenceGenerator",
    parameters = {
        @Parameter(name = "sequence", value = "xyz_id_sequence")
    })
public BigInteger getId()
{
   return id;
}


package com.mycompany.myapp.id;

import org.hibernate.id.SequenceGenerator;

public class BigIntegerSequenceGenerator
    extends SequenceGenerator
{
    @Override
    public Serializable generate(SessionImplementor session, Object obj)
    {
        ...
    }
}

and define the logic in the generate function.

Upvotes: 3

Related Questions