使用hibernate检查数据库中的重复键

时间:2016-08-01 10:14:03

标签: java database hibernate duplicates

  

我设计了两个方法getRandomKey和checkduplicatekey,我需要   知道数据库中是否存在重复密钥。如果存在重复密钥   然后再次调用generateRandomKey方法。简而言之需要Unique键   调用generateRandomkey()方法。

String generateRandomKey() {
        int count = INT_TEN;
        StringBuilder builder = new StringBuilder();
        final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        while (count-- != 0) {
            int character = (int) (Math.random() * ALPHA_NUMERIC_STRING.length());
            builder.append(ALPHA_NUMERIC_STRING.charAt(character));
        }
        String randomkey = builder.toString();
        boolean status = checkDuplicateRandomkey(randomkey);
        if (status==false) {


        }
        return randomkey;
    }


boolean checkDuplicateRandomkey(String randomkey){
        Boolean flag = false;
                Transaction transaction;
                Session session = HibernateUtil.currentSession();
                transaction = session.beginTransaction();
                try {
                    Criteria criteria = session.createCriteria(Employee.class);
                        criteria.add(Restrictions.eq("randomKey", randomkey));
                        criteria.setProjection(Projections.rowCount());
                    int count = ((Long) criteria.uniqueResult()).intValue();
                        transaction.commit();
                       if(count != 0){
                           System.out.println("present");
                           String randomKey=generateRandomKey();
                       }
                       else{
                           System.out.println("absent");
                           flag=false;
                       }
                } catch (Exception exception) {
                    logger.error("Exception : ", exception);
                } finally {
                    HibernateUtil.closeSession();
                }
                return flag;

1 个答案:

答案 0 :(得分:0)

首先,假设您正在使用JPA,我强烈建议您使用javax.persistence.GeneratedValue值,如:

@Id
@GeneratedValue
private Long id;

如果你真的想使用UID,我会这样做,没有必要检查它是否是唯一的:

UUID.randomUUID().toString().replaceAll("-", "").substring(0, 20)

如果要将其剪切为0,20,则会生成如下字符串:

1066c717c8154ab5aeab