📄 sequence.java
字号:
package hong.javanet.dao.util;
import java.sql.*;
import java.util.*;
import org.hibernate.*;
import hong.javanet.dao.*;
public class Sequence {
private String name;
private int currentID;
static private HashMap sequences = new HashMap();
public int CACHE = 100;
public boolean DEBUG = true;
protected Connection getConnection() {
try {
return HibernateUtil.currentSession().connection();
}
catch (HibernateException ex) {
return null;
}
}
private Sequence(String name) {
if(this.DEBUG) {
this.CACHE = 1;
}
try {
this.name = name;
Connection con = this.getConnection();
PreparedStatement psSelect = con.prepareStatement(
"select value from mysequence where name=?");
psSelect.setString(1, name);
ResultSet rs = psSelect.executeQuery();
if (rs.next()) {
this.currentID = rs.getInt(1);
psSelect.close();
rs.close();
} else {
PreparedStatement psInsert = con.prepareStatement(
"insert into mysequence(name,value) values(?,?)");
psInsert.setString(1, name);
psInsert.setInt(2, 0);
int rowcount = psInsert.executeUpdate();
psInsert.close();
if (rowcount == 0) {
throw new RuntimeException("创建序列 "+this.name+" 出错!:" + name);
}
this.currentID = 0;
}
} catch (SQLException ex) {
throw new RuntimeException("创建序列 "+this.name+" 出错!:" + ex.getMessage(), ex);
}
}
public synchronized int nextVal() {
try {
if (this.currentID % this.CACHE == 0) {
PreparedStatement ps = this.getConnection().prepareStatement(
"update mysequence set value=value+? where name=?");
ps.setInt(1, this.CACHE);
ps.setString(2, this.name);
int row = ps.executeUpdate();
ps.close();
if (row == 0) {
throw new RuntimeException("序列 "+this.name+" 应该存在,但是可能不存在!");
}
if(this.DEBUG) {
ps = this.getConnection().prepareStatement(
"select value from mysequence where name=?");
ps.setString(1, this.name);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
this.currentID = rs.getInt(1) - this.CACHE;
} else {
throw new RuntimeException("序列 " + this.name +
" 应该存在,但是可能不存在!");
}
}
}
return ++this.currentID;
} catch (SQLException ex) {
throw new RuntimeException("取序列 "+this.name+" 值出错!" + ex.getMessage(), ex);
}
}
public static synchronized Sequence getInstance(String name) {
name = name.toLowerCase();
Sequence seq = (Sequence) sequences.get(name);
if (seq == null) {
seq = new Sequence(name);
sequences.put(name,seq);
}
return seq;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -