mlczhg 发表于 2016-10-20 07:10:08

java应用使用mysql数据库需要序列的简单实现方法

  mysql方面准备:
  1、在mysql新建一个表,用来存放序列当前值的:

CREATE TABLE `sequenceid_table` (
`sequenceid_table_id` int(11) NOT NULL AUTO_INCREMENT,
`sequenceid_table_name` varchar(50) DEFAULT NULL COMMENT '项目名',
`sequenceid_table_value` bigint(20) DEFAULT NULL COMMENT '值',
PRIMARY KEY (`sequenceid_table_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
  2、插入一条默认数据:
  

INSERT INTO `sequenceid_table` VALUES ( 'studentId', '100000001');
  
  
  java方面:
创建序列工具类:

/**
* 获取序列工具
*
*/
public class SequenceIDUtil {
private static SequenceIDUtil sequenceIDUtil=null;
public SequenceIDUtil(){
}
public synchronized static SequenceIDUtil getInstance() {
if(sequenceIDUtil==null){
sequenceIDUtil=new SequenceIDUtil();
}
return sequenceIDUtil;
}
/**
* 学号
* @return
*/
public long studentId(){
synchronized (this) {
long studentId=0;
try{
BaseDao dao=new BaseDao();
String sql="select t.sequenceid_table_value from sequenceid_table t where t.sequenceid_table_name='studentId'";
studentId=dao.getValueBySql(sql);
String updateSql="UPDATE sequenceid_table t set t.sequenceid_table_value="+(studentId+1)+" where t.sequenceid_table_name='studentId'";
dao.excueSql(updateSql);
}catch(Exception e){
e.printStackTrace();
return 0;
}
return studentId;
}
}
}
  
  
  使用方法:
  
  

public static void main(String[] arg){
System.out.println(SequenceIDUtil.getInstance().studentId()+"");
}
  
  这是比较简单的实现方法,解决了java用mysql时序列的问题。使用的时候只有一个实例,保证了序列的唯一性。
页: [1]
查看完整版本: java应用使用mysql数据库需要序列的简单实现方法