01: package biz.hammurapi.sql;
02:
03: import java.sql.Connection;
04: import java.sql.SQLException;
05: import java.text.MessageFormat;
06:
07: /**
08: * Generates identities using SQLProcessor nextPK method
09: * @author Pavel Vlasov
10: *
11: */
12: public class OracleSequenceIdentityGenerator implements
13: IdentityGenerator {
14:
15: /**
16: * Default constructor with "{0}_SEQ" pattern
17: */
18: public OracleSequenceIdentityGenerator() {
19: this ("{0}_SEQ");
20: }
21:
22: private int mode; // 0 - passthrough 1 - invariant 2 - format
23: private String seqName;
24: private MessageFormat mf;
25: private Object[] args = new Object[] { null };
26:
27: /**
28: * Constructor
29: * @param pattern - Key name pattern. {0} stands for table name.
30: */
31: public OracleSequenceIdentityGenerator(String pattern) {
32: if ("{0}".equals(pattern)) {
33: mode = 0;
34: } else if (pattern.indexOf("{0}") == -1) {
35: mode = 1;
36: this .seqName = pattern;
37: } else {
38: mode = 2;
39: mf = new MessageFormat(pattern);
40: }
41: }
42:
43: public int generate(Connection con, String name)
44: throws SQLException {
45: String ename;
46: switch (mode) {
47: case 0:
48: ename = name + "_SEQ";
49: break;
50: case 1:
51: ename = seqName;
52: break;
53: case 2:
54: synchronized (mf) {
55: args[0] = name;
56: ename = mf.format(args, new StringBuffer(), null)
57: .toString();
58: }
59: default:
60: throw new IllegalStateException("Invalid mode: " + mode);
61: }
62:
63: return new SQLProcessor(con, null).projectSingleInt("SELECT "
64: + ename + ".NEXTVAL FROM DUAL", null);
65: }
66:
67: }
|