简体   繁体   中英

unable to create mysql table using hibernate

Trying to execute a create table query which has a column name with " in it. It seems it errors out everytime, though the string query created works fine on MYSQL browser.

Sysout to createStmt gives:

Create table `myschema`.`flatTest_data_tbl`(`NAME` longtext,`TASK` longtext,`LO&"CATION` longtext) CHARACTER SET utf8

SQLQuery createQuery = session.createSQLQuery(createStmt);
        createQuery.executeUpdate();
        session.close();

It errors out on executeUpdate:

java.util.NoSuchElementException
    at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
    at org.hibernate.engine.jdbc.internal.BasicFormatterImpl$FormatProcess.perform(BasicFormatterImpl.java:142)
    at org.hibernate.engine.jdbc.internal.BasicFormatterImpl.format(BasicFormatterImpl.java:91)
    at org.hibernate.engine.jdbc.spi.SqlStatementLogger.logStatement(SqlStatementLogger.java:101)
    at org.hibernate.engine.jdbc.spi.SqlStatementLogger.logStatement(SqlStatementLogger.java:95)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:180)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareStatement(StatementPreparerImpl.java:91)
    at org.hibernate.engine.query.spi.NativeSQLQueryPlan.performExecuteUpdate(NativeSQLQueryPlan.java:196)
    at org.hibernate.internal.SessionImpl.executeNativeUpdate(SessionImpl.java:1313)
    at org.hibernate.internal.SQLQueryImpl.executeUpdate(SQLQueryImpl.java:401)

I admit picking names can sometimes be a horror, especially if those names are being processed by several tools. For instance, you pick a name that is a keyword in some DBMS, but your relational mapper doesn't care. The error thrown by the database is then wrapped and obscured by the mapper and you need hours to find out what you did wrong.

Furthermore, consider encoding issues when strings are serialized. Especially when sending non-ASCII characters over the web or reading data from files, it is very likely you'll find your original input string doesn't look like the one you pop from the pipe eventually.

For those reasons your approach is grossly negligent. Be glad that your codes breaks right at the start and not in production.

However, in order to find a solution, what about this:

Create a second table with following columns

s_label:VARCHAR(1024),
t_value:LONGTEXT

and add a foreign key to this table from your original table. The column name from the file goes into s_label and you are free to fill it with any characters you like.

This might be a little overhead for the table join, but much more important: it's clean :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM