JDBC操作id(uuid.hex)自动生成类

本文介绍了一个用于生成唯一标识符(UUID)的Java类实现。该类通过组合IP地址、JVM启动时间、计数器等信息生成十六进制格式的UUID,确保了ID的唯一性。此外,还展示了如何在实际应用中使用此类。

package cn.createsoft.saas.util;

import java.net.InetAddress;

/**
* UUID.HEX生成器
*
* @author dengyang
* <br />
* 日期: Jun 10, 2010
* 时间: 7:47:49 AM
*/
public class UUIDHexGenerator {
private String sep = "";

private static final int IP;

private static short counter = (short) 0;

private static final int JVM = (int)(System.currentTimeMillis() >>> 8);

private static UUIDHexGenerator uuidgen = new UUIDHexGenerator();

static {

   int ipadd;
   try {
    ipadd = toInt(InetAddress.getLocalHost().getAddress());
   } catch (Exception e) {
    ipadd = 0;
   }
   IP = ipadd;
}

public static UUIDHexGenerator getInstance() {
   return uuidgen;
}

public static int toInt(byte[] bytes) {
   int result = 0;
   for (int i = 0; i < 4; i++) {
    result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i];
   }
   return result;
}

protected String format(int intval) {
   String formatted = Integer.toHexString(intval);
   StringBuffer buf = new StringBuffer("00000000");
   buf.replace(8 - formatted.length(), 8, formatted);
   return buf.toString();
}

protected String format(short shortval) {
   String formatted = Integer.toHexString(shortval);
   StringBuffer buf = new StringBuffer("0000");
   buf.replace(4 - formatted.length(), 4, formatted);
   return buf.toString();
}

protected int getJVM() {
   return JVM;
}

protected synchronized short getCount() {
   if (counter < 0) {
    counter = 0;
   }
   return counter++;
}

protected int getIP() {
   return IP;
}

protected short getHiTime() {
   return (short) (System.currentTimeMillis() >>> 32);
}

protected int getLoTime() {
   return (int) System.currentTimeMillis();
}

public String generate() {
   return new StringBuffer(36).append(format(getIP())).append(sep).append(
     format(getJVM())).append(sep).append(format(getHiTime()))
     .append(sep).append(format(getLoTime())).append(sep).append(
       format(getCount())).toString();
}

public static void main(String[] str) {
   UUIDHexGenerator id = new UUIDHexGenerator();
   for (int i = 0; i <= 100; i++) {
    System.out.println(id.generate());
   }
   System.out.println("40288182291d1bf501291d1bf5be0000".length());
}

}

--调用uuid.hex生成类

/**
* 解析james过滤的邮件 保存收件到收件人垃圾箱中
*
* @param message
* @param tool
*/
public void saveMail(MimeMessage message, EmailTools tool,
    String userFolderId,String acceptor,String from) {
   PreparedStatement ps = null;
   ConnectDB conndb=null;
   Connection cn=null;
   try {
    conndb = new ConnectDB();
    cn = conndb.getConnection();
   } catch (Exception e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }
   try {
    TrashMail2Chinese m2c = new TrashMail2Chinese();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    message.writeTo(bos);
    byte bMsg[] = bos.toByteArray();
    bos.close();
    String messageName = (new SimpleDateFormat("yyyyMMddHHmmssSSS"))
      .format(new Date());
    // 保存库中sql
    ps = cn
      .prepareStatement("insert into inbox(MESSAGE_NAME,REPOSITORY_NAME,MESSAGE_STATE,SENDER,RECIPIENTS,REMOTE_HOST,REMOTE_ADDR,LAST_UPDATED,MESSAGE_BODY,MESSAGE_ATTRIBUTES) "
        + " values(?,?,?,?,?,?,?,?,empty_Blob(),empty_Blob())");
    ps.setString(1, messageName);
    ps.setString(2, m2c.dealReceiveAddress(message.getFrom())
      .split("@")[0]);
    ps.setString(3, "root");
    ps.setString(4, from);
    ps.setString(5, acceptor);
    ps.setString(6, "localhost");
    ps.setString(7, "127.0.0.1");
    ps.setDate(8, new java.sql.Date((new Date()).getTime()));
    int num = ps.executeUpdate();
    // 查询邮件入库信息
    ps = cn
      .prepareStatement("select MESSAGE_BODY,MESSAGE_ATTRIBUTES from inbox where MESSAGE_NAME = ? for update");
    ps.setString(1, messageName);
    ResultSet rs = ps.executeQuery();
    if (rs.next()) {
     Blob blob = (Blob) rs.getBlob("MESSAGE_BODY");
     blob.setBytes(1, bMsg);
     Blob blob2 = (Blob) rs.getBlob("MESSAGE_ATTRIBUTES");
     blob2.setBytes(1, bMsg);
     // 更新邮件,邮件内容Blob 更新入库
     ps = cn.prepareStatement("update inbox set MESSAGE_BODY=? ,MESSAGE_ATTRIBUTES = ? where MESSAGE_NAME = ?");
     ps.setBlob(1, blob);
     ps.setBlob(2, blob2);
     ps.setString(3, messageName);
     ps.executeUpdate();
    }
    // 把邮件存入用户"垃圾邮件"文件夹中
    if (null != userFolderId && null != messageName) {
     UUIDHexGenerator uuid = new UUIDHexGenerator();
     ps = cn
       .prepareStatement("insert into cs_oa_mail_folder_msg(id,folder_id,mail_number) values(?,?,?)");
     ps.setString(1, uuid.generate());
     ps.setString(2, userFolderId);
     ps.setString(3, messageName);
     int r =ps.executeUpdate();
    }
    cn.commit();
   } catch (Exception e) {
    e.printStackTrace();
   } finally {
    try {
     if (ps != null) {
      ps.close();
     }
     if (!cn.isClosed())
      conndb.closeConnection();
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
}

初始化检查过程中发生异常 org.springframework.dao.DuplicateKeyException: ### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '3005492/2910003' for key 'related_code_unique_idx' ### The error may exist in com/ida/risk/score/dao/rc/StatsRelatedUserDepositMapper.java (best guess) ### The error may involve com.ida.risk.score.dao.rc.StatsRelatedUserDepositMapper.batchInsert-Inline ### The error occurred while setting parameters ### SQL: INSERT INTO stats_related_user_deposit ( user_id, address, tag, related_user_id, channel_id, related_channel_id, related_code, create_time, update_time ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) , (?, ?, ?, ?, ?, ?, ?, ?, ?) ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '3005492/2910003' for key 'related_code_unique_idx' ; Duplicate entry '3005492/2910003' for key 'related_code_unique_idx'; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '3005492/2910003' for key 'related_code_unique_idx' at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:242) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72) at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:88) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:440) at com.sun.proxy.$Proxy143.insert(Unknown Source) at org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:271) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:62) at org.apache.ibatis.binding.MapperProxy$PlainMethodInvoker.invoke(MapperProxy.java:144) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:85) at com.sun.proxy.$Proxy293.batchInsert(Unknown Source) at com.ida.risk.score.service.StatsSpotDepositRelativeService.handleRelatedData(StatsSpotDepositRelativeService.java:169) at com.ida.risk.score.service.StatsSpotDepositRelativeService.performFullDataCleaning(StatsSpotDepositRelativeService.java:76) at com.ida.risk.score.service.StatsSpotDepositRelativeService.performAllDataCleaning(StatsSpotDepositRelativeService.java:54) at com.ida.risk.score.service.StatsSpotDepositRelativeService$$FastClassBySpringCGLIB$$9634a32d.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:684) at com.ida.risk.score.service.StatsSpotDepositRelativeService$$EnhancerBySpringCGLIB$$4c5e6983.performAllDataCleaning(<generated>) at com.ida.risk.score.schedule.SpotDepositSchedule.executeFullData(SpotDepositSchedule.java:42) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:750) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '3005492/2910003' for key 'related_code_unique_idx' at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) at com.mysql.jdbc.Util.getInstance(Util.java:408) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3978) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3914) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2530) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2683) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2495) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1903) at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1242) at com.zaxxer.hikari.pool.ProxyPreparedStatement.execute(ProxyPreparedStatement.java:44) at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.execute(HikariProxyPreparedStatement.java) at org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:47) at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:74) at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:50) at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117) at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:76) at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:197) at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:184) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:426) ... 27 common frames omitted /** * 生成关联码(确保唯一性) */ private String generateRelatedCode(int userId, int relatedUserId) { return userId + "/" + relatedUserId; }-- risk_bigdata.stats_related_user_deposit definition CREATE TABLE `risk_bigdata`.`stats_related_user_deposit` ( `id` int(20) NOT NULL AUTO_INCREMENT, `user_id` int(11) NOT NULL, `address` varchar(320) DEFAULT NULL, `tag` varchar(160) DEFAULT '充值地址tag', `channel_id` int(11) NOT NULL COMMENT '渠道ID', `related_channel_id` int(11) NOT NULL COMMENT '关联渠道ID', `related_user_id` int(11) NOT NULL COMMENT '关联用户ID', `related_code` varchar(160) DEFAULT NULL COMMENT 'uid+/+related_uid的MD5唯一码', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`), UNIQUE KEY `related_code_unique_idx` (`related_code`), KEY `uid_address_realte_uid_index` (`user_id`,`address`,`tag`,`related_user_id`), KEY `address_tag_idx` (`address`,`tag`), KEY `create_time_uid_idx` (`create_time`,`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=2134 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='用户充值关联关系表';
最新发布
12-27
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值