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 TableIdentityGenerator implements IdentityGenerator {
13:
14: /**
15: * Default constructor with "{0}" pattern
16: */
17: public TableIdentityGenerator(String primaryKeysTable) {
18: this (primaryKeysTable, "{0}");
19: }
20:
21: private int mode; // 0 - passthrough 1 - invariant 2 - format
22: private MessageFormat mf;
23: private String keyName;
24: private String primaryKeysTable;
25: private Object[] args = new Object[] { null };
26:
27: /**
28: * Constructor
29: * @param primaryKeysTable - Table which hold primary keys. See SQLProcessor documentation.
30: * @param pattern - Key name pattern. {0} stands for table name.
31: */
32: public TableIdentityGenerator(String primaryKeysTable,
33: String pattern) {
34: if ("{0}".equals(pattern)) {
35: mode = 0;
36: } else if (pattern.indexOf("{0}") == -1) {
37: mode = 1;
38: this .keyName = pattern;
39: } else {
40: mode = 2;
41: mf = new MessageFormat(pattern);
42: }
43: this .primaryKeysTable = primaryKeysTable;
44: }
45:
46: public int generate(Connection con, String name)
47: throws SQLException {
48: String ename;
49: switch (mode) {
50: case 0:
51: ename = name;
52: break;
53: case 1:
54: ename = keyName;
55: break;
56: case 2:
57: synchronized (mf) {
58: args[0] = name;
59: ename = mf.format(args, new StringBuffer(), null)
60: .toString();
61: }
62: default:
63: throw new IllegalStateException("Invalid mode: " + mode);
64: }
65:
66: return new SQLProcessor(con, null).nextPK(primaryKeysTable,
67: ename);
68: }
69:
70: }
|