01: /*
02: * Created by IntelliJ IDEA.
03: * User: Jacques
04: * Date: Mar 26, 2005
05: * Time: 9:29:01 AM
06: */
07: package com.technoetic.xplanner.db.hibernate;
08:
09: import java.sql.Connection;
10:
11: import org.apache.log4j.Logger;
12: import org.springframework.jdbc.core.JdbcTemplate;
13: import org.springframework.jdbc.datasource.SingleConnectionDataSource;
14:
15: import com.technoetic.xplanner.util.LogUtil;
16:
17: public class IdGenerator {
18: int nextId;
19:
20: protected static final Logger LOG = LogUtil.getLogger();
21:
22: static IdGenerator instance;
23: public static final int NEXT_ID_COL_INDEX = 1;
24:
25: public static String getUniqueId(String prefix) {
26: return prefix + getInstance().getNext();
27: }
28:
29: public static int getNextPersistentId() throws Exception {
30: return getInstance().getFromDB(HibernateHelper.getConnection());
31: }
32:
33: public static void setNextPersistentId(int id) throws Exception {
34: getInstance().setInDB(HibernateHelper.getConnection(), id);
35: }
36:
37: private int getNext() {
38: return nextId++;
39: }
40:
41: private static IdGenerator getInstance() {
42: if (instance == null) {
43: instance = new IdGenerator();
44: }
45: return instance;
46: }
47:
48: private IdGenerator() {
49: try {
50: nextId = getFromDB(HibernateHelper.getConnection());
51: } catch (Exception e) {
52: LOG.error(e);
53: }
54: }
55:
56: public static int getFromDB(Connection connection) throws Exception {
57: return newTemplate(connection).queryForInt(
58: HibernateIdentityGenerator.GET_NEXT_ID_QUERY);
59: }
60:
61: public static void setInDB(Connection connection, int nextValue)
62: throws Exception {
63: newTemplate(connection).update(
64: HibernateIdentityGenerator.SET_NEXT_ID_QUERY,
65: new Object[] { new Integer(nextValue) });
66: }
67:
68: private static JdbcTemplate newTemplate(Connection connection) {
69: return new JdbcTemplate(new SingleConnectionDataSource(
70: connection, true));
71: }
72:
73: public static void main(String[] args) {
74: System.out.println("id=" + getUniqueId("test"));
75: System.out.println("id=" + getUniqueId("test"));
76: System.out.println("id=" + getUniqueId("test"));
77: }
78:
79: }
|