org.hibernate.QueryException: Unmatched braces for alias path

Keywords: Programming SQL

When inserting the insert SQL, the above error is exploded.

In fact, the reason is that the insert into statement is a SQL statement made of manually spelled strings.

When the saved field content has other special symbols or more complex content, such errors are easy to occur, which makes the program unable to parse the SQL statement.

Instead, the field content is extracted and becomes a parameter This is not just to prevent SQL injection.

For example

  String fieldNames = record.getString("fieldNames");
            String[] fieldNamesArray = fieldNames.split(",");

            StringBuilder selectSb = new StringBuilder();
            selectSb.append(" select ").append(fieldNames);
            selectSb.append(" from ").append(pwsTable).
                    append(" where ").append(keyField).append("=?");
            Record recordSelectPwsData = Db.findFirst(selectSb.toString(), value);
            StringBuilder insertSBFileds = new StringBuilder();
            List<Object> params = new ArrayList<>();
            for (String f : fieldNamesArray) {
                Object fobj = recordSelectPwsData.getColumnData().get(f);
//                if (fobj != null) {
//                    if (fobj instanceof Boolean) {
//                        //Boolean type
//                        if (fobj.toString() == "true") {
//                            insertSBFileds.append("b'1'" + " , ");
//                        } else {
//                            insertSBFileds.append("b'0'" + " , ");
//                        }
//
//                    } else {
//                        insertSBFileds.append("'" + fobj + "'" + " , ");
//                    }
//
//                } else {
//                    insertSBFileds.append(fobj + " , ");
//                }

                //Specify parameter insertion to prevent parsing exceptions
                insertSBFileds.append("?" + " , ");
                params.add(fobj);
            }


            StringBuilder builder = new StringBuilder("insert into ").
                    append(pwdTable).append(" (").append(fieldNames).
                    append(",snapshot_time,snapshot_system_id,snapshot_operate_type) ")
                    .append(" VALUES ( ")
                    .append(insertSBFileds.toString()).append(" now(), ").append(systemId).
                            append(",'").append(operateType).append("' ) ");

            Db.execute(builder.toString(), params.toArray());

Posted by shanewang on Sat, 09 Nov 2019 06:03:15 -0800