浏览 1465 次
该帖已经被评为新手帖
|
|
---|---|
作者 | 正文 |
发表时间:2008-05-16
public class SQLMap { private static final String resource = "SqlMap.xml"; private static SqlMapClient sqlMap = null; private static final Logger logger = Logger.getLogger(SQLMap.class); private static SQLMap sql = null; private SQLMap() { } public static SqlMapClient getSQLMap() throws SQLMapException { return sqlMap; } //设置同步 public static synchronized SQLMap getInstance() throws SQLMapException { if (sqlMap == null) { Reader reader = null; try { reader = Resources.getResourceAsReader(resource); sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader); } catch (Exception e) { logger.error("Create SQLMap Instance is error:" + e.getMessage()); throw new SQLMapException(e.getMessage()); } } if (sql == null) sql = new SQLMap(); return sql; } public static void start() throws SQLMapException { try { if (sqlMap == null) getInstance(); sqlMap.startTransaction(); } catch (Exception e) { logger.error("start Transaction is error:" + e.getMessage()); throw new SQLMapException(e.getMessage()); } } public static void end() { try { if (sqlMap != null) sqlMap.endTransaction(); } catch (Exception e) { logger.error("end Transaction is error:" + e.getMessage()); } } public static Object insert(String id, Object obj) throws SQLMapException { try { if (sqlMap != null) return sqlMap.insert(id, obj); } catch (Exception e) { logger.error("insert(String id, Object obj) is error:" + id + ":" + e.getMessage()); throw new SQLMapException(e.getMessage()); } return null; } } (1)我做的自定义表存入sequence public final class SequenceUtil { /** * Get next sequence * @param tableName * @return sequence * @throws SQLException */ @SuppressWarnings("unchecked") public static synchronized long nextVal(String tableName) throws SQLException{ if(tableName==null || tableName.equals("")) throw new SQLException("The name of table is not null!"); int val = 0; try{ Map map = new HashMap(); map.put("name", tableName); Object obj = SQLMap.queryForObject("tb_sequences.query", map); if(obj==null){ map.put("val", 1); SQLMap.insert("tb_sequences.insert", map); }else{ SQLMap.update("tb_sequences.update",map); val = (Integer)obj; } SQLMap.commit(); }catch(SQLException e){ throw new SQLException(e.getMessage()); } return (val+1); } } (3)客户端在多线程调用,会重得插入ID.不能插入唯一SequenceUtil.nextVal("test") public static void main(String[] args){ try{ SQLMap.start(); int i=0; while(true& i<10){ Map map = new HashMap(); map.put("name","feng"); map.put("id",SequenceUtil.nextVal("test")); SQLMap.insert("test.insert", map); SQLMap.commit(); i++; } }catch(SQLException e){ e.printStackTrace(); }finally{ SQLMap.end(); } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |