你可以做这样的事情。我已经做过一段时间了,它基于 PostgreSql 和 iBatis,但你可以理解。
public class Sequence implements Serializable {
private static final long serialVersionUID = 7526471155622776147L;
private String name = null;
private int nextId = 0;
public Sequence () {
}
public Sequence (String name, int nextId) {
this.name = name;
this.nextId = nextId;
}
public final String getName () {
return name;
}
public final void setName (String name) {
this.name = name;
}
public final int getNextId () {
return nextId;
}
public final void setNextId (int nextId) {
this.nextId = nextId;
}
}
public class SequenceSqlMapDao extends SqlMapClientDaoSupport implements SequenceDao {
/**
* This is a generic sequence ID generator that is based on a database
* table called 'SEQUENCE', which contains two columns (NAME, NEXTID).
* <p/>
* This approach should work with any database.
*
* @param name The name of the sequence.
* @return The Next ID
* @
*/
public final synchronized int getNextId(String name) {
Sequence sequence = new Sequence(name, -1);
//Sequence sequence = new Sequence();
sequence = (Sequence) getSqlMapClientTemplate ().queryForObject("getSequence", sequence);
if (sequence == null) {
try {
throw new IllegalArgumentException("Error: SHOOT! A null sequence was returned from the database (could not get next " + name + " sequence).");
} catch (Exception ex) {
Logger.getLogger(SequenceSqlMapDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
Object parameterObject = new Sequence(name, sequence.getNextId() + 1);
getSqlMapClientTemplate ().update("updateSequence", parameterObject);
int nextId = sequence.getNextId();
parameterObject = null;
sequence = null;
return nextId;
}
}
如果不出意外,这与数据库无关。您仍然必须在您的网络服务中公开该方法。PS - 我忘记了我从哪里得到的,否则我会归功于适当的来源。