如何在MySQL中生成大量唯一的随机数

时间:2014-09-10 05:47:09

标签: java mysql

在我的项目中,我需要生成大量(数千个)独特的随机数。到目前为止,我正在使用这种效率不高的解决方案:

public void codeFactory(int count) {
    for (;count > 0; count --) {
        while (true) {
            long code = getRandomCode();
            Long codeStored = em.select("c.code").from("codes c").where("c.code = ?", code)
                .fetchSingle(Long.class);
            if (codeStored == null) {
                // this code has not yet been stored
                break;
            } else {
                // we continue, this code is already stored
                continue;
            }
            ...
        }
        // we have created a unique code
    }
}

有没有办法直接用MySQL创建它们所以我不需要为每个代码访问MySQL?

编辑: 我想生成1000000000000和9999999999999之间的RANDOM数字。

3 个答案:

答案 0 :(得分:4)

让我们考虑一下:

  1. 您的表名为TestTable
  2. 您必须在两个数字min_nummax_number
  3. 之间生成一个随机数
  4. 随机数应该是唯一的,并存储在TestColumn
  5. 你可以做这样的事情

    SELECT FLOOR(RAND() * (<max_number> - <min_num> + 1)) + <min_number> AS random_number
    FROM TestTable 
    WHERE "random_num" NOT IN (SELECT TestColumn FROM TestTable) LIMIT 1
    

答案 1 :(得分:0)

为什么重新发明轮子?存在许多库来生成随机数。例如,请查看apache.commons.math3:

package com.techtrip.labs.stackoverflow;

import org.apache.commons.math3.random.ISAACRandom;

public class GeneralTest {
    public static void main(String[] args) {        
        int[] seed = {19399213, 123219, 32132, 32838};
        ISAACRandom rndGen = new ISAACRandom(seed);
        for (int i = 0; i < 1000; i++){
            System.out.println(String.format("The random value is %d", rndGen.nextLong()));
        }
    }
}

答案 2 :(得分:0)

如果您的目标是生成唯一ID,您也可以使用JPA和序列生成器来执行此操作;有很多策略。

例如,非常简单:

@MappedSuperclass
public abstract class AbstractEntity {

    /** The id. */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    protected Long id;

    /**
     * @return the id
     */
    public Long getId() {
        return id;
    }

    @Override
    public int hashCode() {
..
    }

    @Override
    public boolean equals(Object obj) {
...
    }

@Entity
@Table(name = "Something")
public class Something extends AbstractEntity {
... // rest of Something Body
}

public interface SomethingRepository extends CrudRepository<Something, Long>{

}

// Simple test using initializing bean 
@Component
public class SomethingTest implements InitializingBean {
    @Autowired
    SomethingRepository sRepo;

    @Override
    @Transactional
    public void afterPropertiesSet() throws Exception {
        for (int i = 1; i < 10; i++) {
            sRepo.save(new Something());
        }

        Iterator<Something> i = sRepo.findAll().iterator();

        while(i.hasNext()) {
            Something s = i.next();
            System.out.println(String.format("Next random sequence num %d", s.getId()));
        }
    }
}