View Javadoc

1   /*
2    * Copyright 2000-2004 The Apache Software Foundation.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  /***
17   * User: Clinton Begin
18   * Date: Jul 13, 2003
19   * Time: 7:21:30 PM
20   */
21  package com.ibatis.jpetstore.persistence.sqlmapdao;
22  
23  import com.ibatis.dao.client.DaoException;
24  import com.ibatis.dao.client.DaoManager;
25  import com.ibatis.jpetstore.domain.Sequence;
26  import com.ibatis.jpetstore.persistence.iface.SequenceDao;
27  
28  public class SequenceSqlMapDao extends BaseSqlMapDao implements SequenceDao {
29  
30    public SequenceSqlMapDao(DaoManager daoManager) {
31      super(daoManager);
32    }
33  
34    /***
35     * This is a generic sequence ID generator that is based on a database
36     * table called 'SEQUENCE', which contains two columns (NAME, NEXTID).
37     * <p/>
38     * This approach should work with any database.
39     *
40     * @param name The name of the sequence.
41     * @return The Next ID
42     * @
43     */
44    public synchronized int getNextId(String name) {
45      Sequence sequence = new Sequence(name, -1);
46  
47      sequence = (Sequence) queryForObject("getSequence", sequence);
48      if (sequence == null) {
49        throw new DaoException("Error: A null sequence was returned from the database (could not get next " + name + " sequence).");
50      }
51      Object parameterObject = new Sequence(name, sequence.getNextId() + 1);
52      update("updateSequence", parameterObject);
53  
54      return sequence.getNextId();
55    }
56  
57  }