01: package simpleorm.core;
02:
03: /**
04: This class provides simple bulk data loading facilities which are
05: particularly handy for developing test data. It is used as follows:-
06:
07: <xmp>
08: SConnection.rawJDBC("DELETE FROM XX_EMPLOYEE");
09:
10: SDataLoader empDL = new SDataLoader(Employee.meta);
11:
12: Employee e1 = (Employee)empDL.insert(new String[]{
13: "100", "One00", "123 4567", "50000"});
14:
15: empDL.insert(new String[][]{
16: {"200", "Two00", "123 4567", "50000"},
17: {"200", "Two00", "123 4567", "50000"},
18: {"300", "Three00", "123 4567", "50000"}});
19: </xmp> */
20:
21: public class SDataLoader implements SConstants {
22:
23: SRecordMeta sRecordMeta = null;
24: SFieldMeta sFieldMetas[] = null;
25: SFieldMeta keyMetas[] = null;
26:
27: /** A data loader for record <code>sRecordMeta</code> will load
28: <code>fields</code>. The primary key fields are always
29: implicitly included at the beginning and need not be repeated
30: here. The default for <code>fields</code> is all fields except
31: those flagged <code>SQY_UNQUERIED</code>.*/
32: public SDataLoader(SRecordMeta meta, SFieldMeta[] fields) {
33: this .sRecordMeta = meta;
34: this .sFieldMetas = fields;
35: this .keyMetas = meta.fieldList(SQY_NO_FOREIGN_KEYS
36: | SQY_PRIMARY_KEY | SQY_NO_GENERATED_KEYS);
37: }
38:
39: public SDataLoader(SRecordMeta meta, long sqy_flags) {
40: this (meta, meta.fieldList(sqy_flags | SQY_NO_FOREIGN_KEYS
41: | SQY_NO_GENERATED_KEYS));
42: }
43:
44: public SDataLoader(SRecordMeta meta) {
45: this (meta, 0L);
46: }
47:
48: /** Inserts (or updates) one record in the databases, and returns
49: it. The first element(s) in <code>record</code> contain the
50: primary key field(s), the rest contain the public
51: */
52: public SRecordInstance insertRecord(Object[] record) {
53: /// Primary Key
54: if (record == null || record.length != sFieldMetas.length)
55: throw new SException.Error(sFieldMetas.length
56: + " columns required in parameter array.");
57:
58: /// Set Keys and Query
59: SRecordInstance rec = null;
60: int nrKeys = keyMetas.length;
61: if (nrKeys > 0) {
62: Object[] keys = new Object[nrKeys];
63: for (int kx = 0; kx < nrKeys; kx++)
64: keys[kx] = record[kx];
65: rec = sRecordMeta.findOrCreate(keys, 0, sFieldMetas);
66: } else {
67: rec = sRecordMeta.createWithGeneratedKey();
68: }
69:
70: /// Set column Values
71: for (int cx = nrKeys; cx < sFieldMetas.length; cx++)
72: rec.setObject(sFieldMetas[cx], record[cx]);
73:
74: return rec;
75: }
76:
77: /** Conveniently inserts multiple records in one go. Each inner
78: array is simply passed to <code>insert(String[])</code>.*/
79: public SRecordInstance[] insertRecords(Object[][] records) {
80: SRecordInstance[] res = (SRecordInstance[]) java.lang.reflect.Array
81: .newInstance(sRecordMeta.userClass, records.length);
82: for (int x = 0; x < records.length; x++) {
83: res[x] = insertRecord(records[x]);
84: }
85: return res;
86: }
87:
88: }
|