Reputation: 457
I am building data base system for electronic components. Unfortunatly other programs, that will use some of my tables need to have white spaces in column names. Ive tried in my hbm.xml file something like this with property:
...
property name="partGroup" column="part group" type="string"
...
of course hibernate wont create table with that column name.
Is there a way to do it using hibernate?
Thanks :]
Upvotes: 8
Views: 3989
Reputation: 146
I had solved this problem as follows:
I had create following class:
import org.hibernate.cfg.DefaultNamingStrategy; public class MysqlAdvancedNamingStrategy extends DefaultNamingStrategy{}@Override public String columnName(String columnName) { return "`"+super.columnName(columnName)+"`"; } @Override public String tableName(String tableName) { return "`"+super.tableName(tableName)+"`"; }
I had setting as namingStrategy the "MysqlAdvancedNamingStrategy" at previous point.
The advantages of this solution is that you don't need to modify all annotation in you code.
It is also a clean solution because for some reason you may want have an application that access to same database "logic" in two different "database" (so with two style of escaping), with this solution you can intercept what database are you using and you can change the escaping strategy at "execution time", however the annotation are evalutated at "compilation time".
It is also a clean solution if you use Spring framework, with this you can change the escaping strategy without touching java code by setting a bean in session factory with id="namingStrategy"
and class="util.MysqlAdvancedNamingStrategy"
.
Upvotes: 0
Reputation: 570345
There is a way, enclose the table names or column names with backticks. From the documentation:
5.4. SQL quoted identifiers
You can force Hibernate to quote an identifier in the generated SQL by enclosing the table or column name in backticks in the mapping document. Hibernate will use the correct quotation style for the SQL Dialect. This is usually double quotes, but the SQL Server uses brackets and MySQL uses backticks.
<class name="LineItem" table="`Line Item`"> <id name="id" column="`Item Id`"/><generator class="assigned"/></id> <property name="itemNumber" column="`Item #`"/> ... </class>
Upvotes: 12