Example usage for java.sql Connection isReadOnly

List of usage examples for java.sql Connection isReadOnly

Introduction

In this page you can find the example usage for java.sql Connection isReadOnly.

Prototype

boolean isReadOnly() throws SQLException;

Source Link

Document

Retrieves whether this Connection object is in read-only mode.

Usage

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *  Loades subnodes via subnode relation. This is similar to getNodeIDs, but it
 *  actually loades all nodes in one go, which is better for small node collections.
 *  This method is used when xxx.loadmode=aggressive is specified.
 *///from  w ww  .j  av  a 2  s.c o m
public Collection<NodeHandle> getNodes(Node home, Relation rel) throws Exception {
    // This does not apply for groupby nodes - use getNodeIDs instead
    if (rel.groupby != null) {
        return getNodeIDs(home, rel);
    }

    // Transactor tx = (Transactor) Thread.currentThread ();
    // tx.timer.beginEvent ("getNodes "+home);
    if ((rel == null) || (rel.otherType == null) || !rel.otherType.isRelational()) {
        // this should never be called for embedded nodes
        throw new RuntimeException("NodeMgr.getNodes called for non-relational node " + home);
    } else {
        Collection<NodeHandle> retval = home.createSubnodeList();
        DbMapping dbm = rel.otherType;

        Connection con = dbm.getConnection();
        // set connection to read-only mode
        if (!con.isReadOnly())
            con.setReadOnly(true);

        Statement stmt = con.createStatement();
        DbColumn[] columns = dbm.getColumns();
        Relation[] joins = dbm.getJoins();
        String query = null;
        long logTimeStart = logSql ? System.currentTimeMillis() : 0;

        try {
            StringBuffer b = dbm.getSelect(rel);

            if (home.getSubnodeRelation() != null) {
                b.append(home.getSubnodeRelation());
            } else {
                // let relation object build the query
                b.append(rel.buildQuery(home, home.getNonVirtualParent(), null, " WHERE ", true));
            }

            query = b.toString();

            if (rel.maxSize > 0) {
                stmt.setMaxRows(rel.maxSize);
            }

            ResultSet rs = stmt.executeQuery(query);

            while (rs.next()) {
                // create new Nodes.
                Node node = createNode(rel.otherType, rs, columns, 0);
                if (node == null) {
                    continue;
                }
                Key primKey = node.getKey();

                if (retval instanceof SubnodeList) {
                    ((SubnodeList) retval).addSorted(new NodeHandle(primKey));
                } else {
                    retval.add(new NodeHandle(primKey));
                }

                // do we need to synchronize on primKey here?
                synchronized (cache) {
                    Node oldnode = (Node) cache.put(primKey, node);

                    if ((oldnode != null) && (oldnode.getState() != INode.INVALID)) {
                        cache.put(primKey, oldnode);
                    }
                }

                fetchJoinedNodes(rs, joins, columns.length);
            }

        } finally {
            if (logSql) {
                long logTimeStop = System.currentTimeMillis();
                logSqlStatement("SQL SELECT_ALL", dbm.getTableName(), logTimeStart, logTimeStop, query);
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ignore) {
                    app.logEvent(ignore.getMessage());
                }
            }
        }

        return retval;
    }
}

From source file:axiom.objectmodel.db.NodeManager.java

private Node getNodeByKey(ITransaction txn, DbKey key, String type, boolean multiLayers) throws Exception {
    // Note: Key must be a DbKey, otherwise will not work for relational objects
    Node node = null;/*from   w  w  w.  j  a  v a 2s.  c  o  m*/
    if (type == null) {
        type = key.getStorageName();
    }
    DbMapping dbm = app.getDbMapping(type);
    String kstr = key.getID();

    if ((dbm == null) || !dbm.isRelational()) {
        IDatabase db = this.getDatabaseForMapping(dbm);
        try {
            final int mode;
            if (key instanceof DbKey) {
                // andy maybe i don't know
                /*if(this.app.getCurrentRequestEvaluator().getMode() == DbKey.DRAFT_MODE){
                    mode = this.app.getCurrentRequestEvaluator().getMode();
                }
                else{*/
                mode = ((DbKey) key).getLayer();
                //}
            } else {
                mode = this.app.getCurrentRequestEvaluator().getLayer();
            }
            node = (Node) db.getNode(txn, kstr, mode, multiLayers);
        } catch (Exception ex) {
            if (multiLayers) {
                node = (Node) db.getNode(txn, kstr);
            }
        }
        if (node != null) {
            node.nmgr = safe;
        }

        if ((node != null) && (dbm != null)) {
            node.setDbMapping(dbm);
        }
    } else {
        String idfield = dbm.getIDField();

        Statement stmt = null;
        String query = null;
        long logTimeStart = logSql ? System.currentTimeMillis() : 0;

        try {
            Connection con = dbm.getConnection();
            // set connection to read-only mode
            if (!con.isReadOnly())
                con.setReadOnly(true);

            stmt = con.createStatement();

            DbColumn[] columns = dbm.getColumns();
            Relation[] joins = dbm.getJoins();
            StringBuffer b = dbm.getSelect(null).append("WHERE ")
                    //.append(dbm.getTableName(0))
                    //.append(".")
                    .append(idfield).append(" = ");

            if (dbm.needsQuotes(idfield)) {
                b.append("'");
                b.append(escape(kstr));
                b.append("'");
            } else {
                b.append(kstr);
            }

            dbm.addJoinConstraints(b, " AND ");

            query = b.toString();
            query += dbm.getTableJoinClause(0);

            ResultSet rs = stmt.executeQuery(query);

            if (!rs.next()) {
                return null;
            }

            node = createNode(dbm, rs, columns, 0);

            fetchJoinedNodes(rs, joins, columns.length);

            if (rs.next()) {
                app.logError(ErrorReporter.errorMsg(this.getClass(), "getNodeByKey")
                        + "More than one value returned for query " + query);
            }
        } finally {
            if (logSql) {
                long logTimeStop = System.currentTimeMillis();
                logSqlStatement("SQL SELECT_BYKEY", dbm.getTableName(), logTimeStart, logTimeStop, query);
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ex) {
                    app.logError(ErrorReporter.errorMsg(this.getClass(), "getNodeByKey"), ex);
                }
            }
        }
    }

    return node;
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *  Loades subnodes via subnode relation. Only the ID index is loaded, the nodes are
 *  loaded later on demand./*  ww  w .j a  va  2 s.  c  om*/
 */
public Collection<NodeHandle> getNodeIDs(Node home, Relation rel) throws Exception {
    // Transactor tx = (Transactor) Thread.currentThread ();
    // tx.timer.beginEvent ("getNodeIDs "+home);

    if ((rel == null) || (rel.otherType == null) || !rel.otherType.isRelational()) {
        // this should never be called for embedded nodes
        throw new RuntimeException("NodeMgr.getNodeIDs called for non-relational node " + home);
    } else {
        Collection<NodeHandle> retval = home.createSubnodeList();

        // if we do a groupby query (creating an intermediate layer of groupby nodes),
        // retrieve the value of that field instead of the primary key
        String idfield = (rel.groupby == null) ? rel.otherType.getIDField() : rel.groupby;
        Connection con = rel.otherType.getConnection();
        // set connection to read-only mode
        if (!con.isReadOnly())
            con.setReadOnly(true);

        String table = rel.otherType.getTableName();

        Statement stmt = null;
        long logTimeStart = logSql ? System.currentTimeMillis() : 0;
        String query = null;

        try {
            StringBuffer b = new StringBuffer("SELECT ");

            if (rel.queryHints != null) {
                b.append(rel.queryHints).append(" ");
            }

            /*if (idfield.indexOf('(') == -1 && idfield.indexOf('.') == -1) {
            b.append(table).append('.');
            }*/
            b/*.append(rel.otherType.getTableName(0)).append(".")*/.append(idfield).append(" FROM ")
                    .append(table);

            rel.appendAdditionalTables(b);

            if (home.getSubnodeRelation() != null) {
                // subnode relation was explicitly set
                query = b.append(" ").append(home.getSubnodeRelation()).toString();
            } else {
                // let relation object build the query
                query = b.append(rel.buildQuery(home, home.getNonVirtualParent(), null, " WHERE ", true))
                        .toString();
            }

            stmt = con.createStatement();
            int primary = 1;
            if (query.indexOf("WHERE") > -1) {
                primary = 0;
            }
            query += rel.otherType.getTableJoinClause(primary);

            if (rel.maxSize > 0) {
                stmt.setMaxRows(rel.maxSize);
            }

            ResultSet result = stmt.executeQuery(query);

            // problem: how do we derive a SyntheticKey from a not-yet-persistent Node?
            Key k = (rel.groupby != null) ? home.getKey() : null;

            while (result.next()) {
                String kstr = result.getString(1);

                // jump over null values - this can happen especially when the selected
                // column is a group-by column.
                if (kstr == null) {
                    continue;
                }

                // make the proper key for the object, either a generic DB key or a groupby key
                Key key = (rel.groupby == null)
                        ? (Key) new DbKey(rel.otherType, kstr, this.app.getCurrentRequestEvaluator().getLayer())
                        : (Key) new SyntheticKey(k, kstr);

                if (retval instanceof SubnodeList) {
                    ((SubnodeList) retval).addSorted(new NodeHandle(key));
                } else {
                    retval.add(new NodeHandle(key));
                }

                // if these are groupby nodes, evict nullNode keys
                if (rel.groupby != null) {
                    Node n = this.getNodeFromCache(key);

                    if ((n != null) && n.isNullNode()) {
                        evictKey(key);
                    }
                }
            }
        } finally {
            if (logSql) {
                long logTimeStop = System.currentTimeMillis();
                logSqlStatement("SQL SELECT_IDS", table, logTimeStart, logTimeStop, query);
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ignore) {
                }
            }
        }

        return retval;
    }
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *  Updates a modified node in the embedded db or an external relational database, depending
 * on its database mapping./* w ww .j a  v  a  2 s.com*/
 *
 * @return true if the DbMapping of the updated Node is to be marked as updated via
 *              DbMapping.setLastDataChange
 */
public boolean updateNode(IDatabase db, ITransaction txn, Node node)
        throws IOException, SQLException, ClassNotFoundException {
    // Transactor tx = (Transactor) Thread.currentThread ();
    // tx.timer.beginEvent ("updateNode "+node);
    invokeOnPersist(node);
    DbMapping dbm = node.getDbMapping();
    boolean markMappingAsUpdated = false;

    if ((dbm == null) || !dbm.isRelational()) {
        String className = dbm.getClassName();
        IDatabase idb = null;
        if (className != null) {
            idb = (IDatabase) this.dbs.get(className);
        }
        if (idb == null) {
            idb = db;
        }
        idb.updateNode(txn, node.getID(), node);
    } else {
        Hashtable propMap = node.getPropMap();
        Property[] props;

        if (propMap == null) {
            props = new Property[0];
        } else {
            props = new Property[propMap.size()];
            propMap.values().toArray(props);
        }

        // make sure table meta info is loaded by dbmapping
        dbm.getColumns();

        StringBuffer b = dbm.getUpdate();

        // comma flag set after the first dirty column, also tells as
        // if there are dirty columns at all
        boolean comma = false;

        for (int i = 0; i < props.length; i++) {
            // skip clean properties
            if ((props[i] == null) || !props[i].dirty) {
                // null out clean property so we don't consider it later
                props[i] = null;

                continue;
            }

            Relation rel = dbm.propertyToRelation(props[i].getName());

            // skip readonly, virtual and collection relations
            if ((rel == null) || rel.readonly || rel.virtual
                    || ((rel.reftype != Relation.REFERENCE) && (rel.reftype != Relation.PRIMITIVE))) {
                // null out property so we don't consider it later
                props[i] = null;

                continue;
            }

            if (comma) {
                b.append(", ");
            } else {
                comma = true;
            }

            b.append(rel.getDbField());
            b.append(" = ?");
        }

        // if no columns were updated, return false
        if (!comma) {
            return false;
        }

        b.append(" WHERE ");
        //b.append(dbm.getTableName(0));
        //b.append(".");
        b.append(dbm.getIDField());
        b.append(" = ");

        if (dbm.needsQuotes(dbm.getIDField())) {
            b.append("'");
            b.append(escape(node.getID()));
            b.append("'");
        } else {
            b.append(node.getID());
        }
        b.append(dbm.getTableJoinClause(0));

        Connection con = dbm.getConnection();
        // set connection to write mode
        if (con.isReadOnly())
            con.setReadOnly(false);
        PreparedStatement stmt = con.prepareStatement(b.toString());

        int stmtNumber = 0;
        long logTimeStart = logSql ? System.currentTimeMillis() : 0;

        try {
            for (int i = 0; i < props.length; i++) {
                Property p = props[i];

                if (p == null) {
                    continue;
                }

                Relation rel = dbm.propertyToRelation(p.getName());

                stmtNumber++;
                this.setStatementValues(stmt, stmtNumber, p, rel.getColumnType());

                p.dirty = false;

                if (!rel.isPrivate()) {
                    markMappingAsUpdated = true;
                }
            }

            stmt.executeUpdate();

        } finally {
            if (logSql) {
                long logTimeStop = System.currentTimeMillis();
                logSqlStatement("SQL UPDATE", dbm.getTableName(), logTimeStart, logTimeStop, b.toString());
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ignore) {
                    app.logEvent(ignore.getMessage());
                }
            }
        }
    }

    // update may cause changes in the node's parent subnode array
    // TODO: is this really needed anymore?
    if (markMappingAsUpdated && node.isAnonymous()) {
        Node parent = node.getCachedParent();

        if (parent != null) {
            parent.setLastSubnodeChange(System.currentTimeMillis());
        }
    }

    return markMappingAsUpdated;
}

From source file:axiom.objectmodel.db.NodeManager.java

private Node getNodeByRelation(ITransaction txn, Node home, String kstr, Relation rel, String type)
        throws Exception {
    Node node = null;/*from   w w  w . jav  a  2  s  . c  o  m*/
    boolean updateTypeDirty = false;

    if ((rel != null) && rel.virtual) {
        if (rel.needsPersistence()) {
            node = (Node) home.createNode(kstr);
        } else {
            node = new Node(home, kstr, safe, rel.prototype);
        }

        // set prototype and dbmapping on the newly created virtual/collection node
        node.setPrototype(rel.prototype);
        node.setDbMapping(rel.getVirtualMapping());
    } else if ((rel != null) && (rel.groupby != null)) {
        node = home.getGroupbySubnode(kstr, false);

        if ((node == null) && ((rel.otherType == null) || !rel.otherType.isRelational())) {

            IDatabase db = this.getDatabaseForMapping(rel.otherType);
            try {
                node = (Node) db.getNode(txn, kstr, this.app.getCurrentRequestEvaluator().getLayer());
            } catch (Exception ex) {
                node = (Node) db.getNode(txn, kstr);
            }
            node.nmgr = safe;
        }

        return node;
    } else if ((rel == null) || (rel.otherType == null) || !rel.otherType.isRelational()) {

        IDatabase db = (rel == null) ? this.defaultDb : this.getDatabaseForMapping(rel.otherType);
        try {
            node = (Node) ((LuceneDatabase) db).getNode(txn, kstr,
                    this.app.getCurrentRequestEvaluator().getLayer());
        } catch (Exception ex) {
            node = (Node) db.getNode(txn, kstr);
        }
        node.nmgr = safe;
        node.setDbMapping(rel.otherType);

        return node;
    } else {
        //DbMapping dbm = rel.otherType;
        DbMapping dbm = rel.otherType;
        if (type != null) {
            dbm = this.getDbMapping(type);
            //set the DbMapping later?
            updateTypeDirty = true;
        }
        Statement stmt = null;
        String query = null;
        long logTimeStart = logSql ? System.currentTimeMillis() : 0;

        try {
            Connection con = dbm.getConnection();
            // set connection to read-only mode
            if (!con.isReadOnly())
                con.setReadOnly(true);
            DbColumn[] columns = dbm.getColumns();
            Relation[] joins = dbm.getJoins();
            StringBuffer b = dbm.getSelect(rel);
            if (home.getSubnodeRelation() != null && !rel.isComplexReference()) {
                // combine our key with the constraints in the manually set subnode relation
                b.append(" WHERE ");
                if (rel.accessName.indexOf('(') == -1 && rel.accessName.indexOf('.') == -1) {
                    b.append(dbm.getTableName(0));
                    b.append(".");
                }
                b.append(rel.accessName);
                b.append(" = '");
                b.append(escape(kstr));
                b.append("'");
                // add join contraints in case this is an old oracle style join
                dbm.addJoinConstraints(b, " AND ");
                // add potential constraints from manually set subnodeRelation
                String subrel = home.getSubnodeRelation().trim();
                if (subrel.length() > 5) {
                    b.append(" AND (");
                    b.append(subrel.substring(5).trim());
                    b.append(")");
                }
            } else {
                b.append(rel.buildQuery(home, home.getNonVirtualParent(), kstr, " WHERE ", false));
            }

            b.append(dbm.getTableJoinClause(0));

            stmt = con.createStatement();

            query = b.toString();

            ResultSet rs = stmt.executeQuery(query);

            if (!rs.next()) {
                return null;
            }

            //node = createNode(rel.otherType, rs, columns, 0);
            node = createNode(dbm, rs, columns, 0);

            fetchJoinedNodes(rs, joins, columns.length);

            if (rs.next()) {
                app.logError(ErrorReporter.errorMsg(this.getClass(), "getNodeByRelation")
                        + "More than one value returned for query " + query);
            }

            // Check if node is already cached with primary Key.
            if (!rel.usesPrimaryKey() && node != null) {
                Key pk = node.getKey();
                Node existing = this.getNodeFromCache(pk);

                if ((existing != null) && (existing.getState() != Node.INVALID) && (!updateTypeDirty)) { //Check for dirty bit!
                    node = existing;
                }
            }

        } finally {
            if (logSql) {
                long logTimeStop = System.currentTimeMillis();
                logSqlStatement("SQL SELECT_BYRELATION", dbm.getTableName(), logTimeStart, logTimeStop, query);
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ex) {
                    app.logError(ErrorReporter.errorMsg(this.getClass(), "getNodeByRelation"), ex);
                }
            }
        }
    }

    if ((node != null) && (updateTypeDirty)) {
        node.setTypeDirty(false);
    }

    return node;
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *
 *///from  w w  w.j  a va 2s. c o  m
public void prefetchNodes(Node home, Relation rel, Key[] keys) throws Exception {
    DbMapping dbm = rel.otherType;

    if ((dbm == null) || !dbm.isRelational()) {
        // this does nothing for objects in the embedded database
        return;
    } else {
        boolean missing = missingFromCache(keys);

        if (missing) {
            Connection con = dbm.getConnection();
            // set connection to read-only mode
            if (!con.isReadOnly())
                con.setReadOnly(true);

            Statement stmt = con.createStatement();
            DbColumn[] columns = dbm.getColumns();
            Relation[] joins = dbm.getJoins();
            String query = null;
            long logTimeStart = logSql ? System.currentTimeMillis() : 0;

            try {
                StringBuffer b = dbm.getSelect(rel);

                String idfield = (rel.groupby != null) ? rel.groupby : dbm.getIDField();
                boolean needsQuotes = dbm.needsQuotes(idfield);

                b.append(" WHERE ");
                //b.append(dbm.getTableName());
                //b.append(".");
                b.append(idfield);
                b.append(" IN (");

                boolean first = true;

                for (int i = 0; i < keys.length; i++) {
                    if (keys[i] != null) {
                        if (!first) {
                            b.append(',');
                        } else {
                            first = false;
                        }

                        if (needsQuotes) {
                            b.append("'");
                            b.append(escape(keys[i].getID()));
                            b.append("'");
                        } else {
                            b.append(keys[i].getID());
                        }
                    }
                }

                b.append(") ");

                dbm.addJoinConstraints(b, " AND ");

                if (rel.groupby != null) {
                    rel.renderConstraints(b, home, home.getNonVirtualParent(), " AND ");

                    if (rel.order != null) {
                        b.append(" ORDER BY ");
                        b.append(rel.order);
                    }
                }

                query = b.toString();

                ResultSet rs = stmt.executeQuery(query);

                String groupbyProp = null;
                HashMap groupbySubnodes = null;

                if (rel.groupby != null) {
                    groupbyProp = dbm.columnNameToProperty(rel.groupby);
                    groupbySubnodes = new HashMap();
                }

                String accessProp = null;

                if ((rel.accessName != null) && !rel.usesPrimaryKey()) {
                    accessProp = dbm.columnNameToProperty(rel.accessName);
                }

                while (rs.next()) {
                    // create new Nodes.
                    Node node = createNode(dbm, rs, columns, 0);
                    if (node == null) {
                        continue;
                    }
                    Key primKey = node.getKey();

                    // for grouped nodes, collect subnode lists for the intermediary
                    // group nodes.
                    String groupName = null;

                    if (groupbyProp != null) {
                        groupName = node.getString(groupbyProp);

                        SubnodeList sn = (SubnodeList) groupbySubnodes.get(groupName);

                        if (sn == null) {
                            sn = new SubnodeList(safe, rel);
                            groupbySubnodes.put(groupName, sn);
                        }

                        sn.addSorted(new NodeHandle(primKey));
                    }

                    // if relation doesn't use primary key as accessName, get accessName value
                    String accessName = null;

                    if (accessProp != null) {
                        accessName = node.getString(accessProp);
                    }

                    // register new nodes with the cache. If an up-to-date copy
                    // existed in the cache, use that.
                    synchronized (cache) {
                        Node oldnode = (Node) cache.put(primKey, node);

                        if ((oldnode != null) && (oldnode.getState() != INode.INVALID)) {
                            // found an ok version in the cache, use it.
                            cache.put(primKey, oldnode);
                        } else if (accessName != null) {
                            // put the node into cache with its secondary key
                            if (groupName != null) {
                                cache.put(new SyntheticKey(new SyntheticKey(home.getKey(), groupName),
                                        accessName), node);
                            } else {
                                cache.put(new SyntheticKey(home.getKey(), accessName), node);
                            }
                        }
                    }

                    fetchJoinedNodes(rs, joins, columns.length);
                }

                // If these are grouped nodes, build the intermediary group nodes
                // with the subnod lists we created
                if (groupbyProp != null) {
                    for (Iterator i = groupbySubnodes.keySet().iterator(); i.hasNext();) {
                        String groupname = (String) i.next();

                        if (groupname == null) {
                            continue;
                        }

                        Node groupnode = home.getGroupbySubnode(groupname, true);

                        groupnode.setSubnodes((SubnodeList) groupbySubnodes.get(groupname));
                        groupnode.lastSubnodeFetch = System.currentTimeMillis();
                    }
                }
            } catch (Exception x) {
                System.err.println("Error in prefetchNodes(): " + x);
            } finally {
                if (logSql) {
                    long logTimeStop = System.currentTimeMillis();
                    logSqlStatement("SQL SELECT_PREFETCH", dbm.getTableName(), logTimeStart, logTimeStop,
                            query);
                }
                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (Exception ignore) {
                        app.logEvent(ignore.getMessage());
                    }
                }
            }
        }
    }
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 * Insert a node into a relational database.
 *//*w  w  w  .j  av  a  2 s  .  c o  m*/
protected void insertRelationalNodeInto(Node node, DbMapping dbm, Connection con, int tableNumber)
        throws ClassNotFoundException, SQLException {

    if (con == null) {
        throw new NullPointerException("Error inserting relational node: Connection is null");
    }

    // set connection to write mode
    if (con.isReadOnly())
        con.setReadOnly(false);

    String insertString = dbm.getInsert(tableNumber);

    PreparedStatement stmt = con.prepareStatement(insertString);

    DbColumn[] columns = dbm.getColumns(tableNumber);

    String nameField = dbm.getNameField();
    String prototypeField = dbm.getPrototypeField();
    String idField = dbm.getTableKey(tableNumber);

    long logTimeStart = logSql ? System.currentTimeMillis() : 0;

    try {
        int stmtNumber = 1;

        // first column of insert statement is always the primary key
        // Changed to get the primary key value from the db mapping,
        // in the case where a particular table's primary key is not the primary key
        // of the main table in the db mapping.
        stmt.setString(stmtNumber, dbm.getPrimaryKeyValue(node, tableNumber)); //node.getID());

        Hashtable propMap = node.getPropMap();

        for (int i = 0; i < columns.length; i++) {
            Relation rel = columns[i].getRelation();
            Property p = null;

            if (rel != null && propMap != null && (rel.isPrimitive() || rel.isReference())) {
                p = (Property) propMap.get(rel.getPropName());
            }

            String name = columns[i].getName();
            if (name.equals(idField)) {
                continue;
            } //Ensure the id is not repeated.

            if (!((rel != null) && (rel.isPrimitive() || rel.isReference()))
                    && !name.equalsIgnoreCase(nameField) && !name.equalsIgnoreCase(prototypeField)) {
                continue;
            }

            stmtNumber++;
            if (p != null) {
                this.setStatementValues(stmt, stmtNumber, p, columns[i].getType());
            } else if (name.equalsIgnoreCase(nameField)) {
                stmt.setString(stmtNumber, node.getName());
            } else if (name.equalsIgnoreCase(prototypeField)) {
                stmt.setString(stmtNumber, node.getPrototype());
            } else {
                stmt.setNull(stmtNumber, columns[i].getType());
            }
        }

        stmt.executeUpdate();
        //            node.setInteger("id", new Integer(node.getID()).longValue());

    } finally {
        if (logSql) {
            long logTimeStop = java.lang.System.currentTimeMillis();
            logSqlStatement("SQL INSERT", dbm.getTableName(), logTimeStart, logTimeStop, insertString);
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (Exception ex) {
                app.logError(ErrorReporter.errorMsg(this.getClass(), "insertRelationalNodeInto"), ex);
            }
        }
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

public void beginUpdate() throws WGAPIException {
    try {/*from ww w  . ja va2s  .  c  o  m*/
        getSession().getTransaction().rollback();

        getSession().doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                if (connection.isReadOnly()) {
                    connection.setReadOnly(false);
                }
            }
        });

        String user = _db.getSessionContext().getUser();
        DBUpdate update = new DBUpdate(_db.getSessionContext());
        _dbUpdatesByUser.put(user, update);

        getSession().beginTransaction();
    } catch (HibernateException e) {
        throw new WGBackendException("unable to start transaction", e);
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

public void commitHibernateTransaction() throws WGAPIException {
    if (getTransactionMode() != WGSessionContext.TRANSACTION_MODE_MANUAL) {
        Transaction trans = getSession().getTransaction();
        if (trans != null) {
            trans.commit();//from w w w.  ja  va2s. c om
        }

        // hibernate might release the underlying jdbc connection after commit
        // and get a new one
        // this connection will be readonly by default - therefore we should
        // check if we have to
        // make it read/write
        if (isUpdateInProgress()) {
            try {
                getSession().doWork(new Work() {
                    public void execute(Connection connection) throws SQLException {
                        if (connection.isReadOnly()) {
                            connection.setReadOnly(false);
                        }
                    }
                });
            } catch (HibernateException e) {
                throw new WGBackendException("unable to establish a read/write connection.", e);
            }
        }

        getSession().beginTransaction();
    } else {
        // perform at least a flush in this mode so JDBC driver will execute changes in current JDBC transaction
        getSession().flush();
    }
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

protected void rollbackHibernateTransaction(boolean noThrows) throws WGAPIException {

    if (getTransactionMode() != WGSessionContext.TRANSACTION_MODE_MANUAL) {

        try {//from   w  ww. j a v a  2 s. co m
            Transaction trans = getSession().getTransaction();
            if (trans != null && trans.isActive()) {
                trans.rollback();
            }

            // hibernate might release the underlying jdbc connection after commit
            // and get a new one
            // this connection will be readonly by default - therefore we should
            // check if we have to
            // make it read/write
            if (isUpdateInProgress()) {
                try {
                    getSession().doWork(new Work() {
                        public void execute(Connection connection) throws SQLException {
                            if (connection.isReadOnly()) {
                                connection.setReadOnly(false);
                            }
                        }
                    });

                } catch (HibernateException e) {
                    throw new WGBackendException("unable to establish a read/write connection.", e);
                }
            }

            getSession().beginTransaction();
        } catch (Throwable e) {
            if (noThrows) {
                WGFactory.getLogger().error(
                        "Exception rolling back transaction. Cause for rollback may be logged after this exception.",
                        e);
            } else if (e instanceof WGBackendException) {
                throw (WGBackendException) e;
            } else if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            } else {
                throw new WGBackendException("Exception rolling back transaction", e);
            }
        }

    }

}