读了ibatis的jpetstore源程序,有个关于synchronized的问题请教一下

05-10-29 kevinleepk
在看jpetstore的源程序时,发现里面有个生成序列号dao实现类,通过名称找到当前数据库中该类别的序列号,将取出的序列号加1并更新到数据库中,同时返回加1前的序列号,这个方法名前有个synchronized关键字。请问如果在真实环境下采用这种方法会不会有问题?是否需要将该方法定义为static方法?或对该类采用singleton的模式?

代码如下

/**

* User: Clinton Begin

* Date: Jul 13, 2003

* Time: 7:21:30 PM

*/

package com.ibatis.jpetstore.persistence.sqlmapdao;

import com.ibatis.dao.client.DaoException;

import com.ibatis.dao.client.DaoManager;

import com.ibatis.jpetstore.domain.Sequence;

import com.ibatis.jpetstore.persistence.iface.SequenceDao;

public class SequenceSqlMapDao extends BaseSqlMapDao implements SequenceDao {

public SequenceSqlMapDao(DaoManager daoManager) {

super(daoManager);

}

/**

* 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 synchronized int getNextId(String name) {

Sequence sequence = new Sequence(name, -1);

sequence = (Sequence) queryForObject("getSequence", sequence);

if (sequence == null) {

throw new DaoException("Error: A null sequence was returned from the database (could not get next " + name + " sequence).");

}

Object parameterObject = new Sequence(name, sequence.getNextId() + 1);

update("updateSequence", parameterObject);

return sequence.getNextId();

}

}

banq
2005-11-01 09:42
序列号需要严格事务处理以及业务逻辑运算,所以jpetstore的序列号只是适合访问量不大的情况。

猜你喜欢