Main Tutorials

Hibernate – Unable to insert if column named is keyword, such as DESC

Problem

A table named “category” in MySQL database, contains a “DESC” keyword as column name.


CREATE TABLE `category` (
  `CATEGORY_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `NAME` varchar(10) NOT NULL,
  `DESC` varchar(255) NOT NULL,
  PRIMARY KEY (`CATEGORY_ID`) USING BTREE
);

Hibernate XML mapping file


<hibernate-mapping>
    <class name="com.mkyong.stock.Category" table="category" catalog="mkyongdb">
        ...
        <property name="desc" type="string">
            <column name="DESC" not-null="true" />
        </property>
       ...
    </class>
</hibernate-mapping>

Or Hibernate annotation


@Column(name = "DESC", nullable = false)
	public String getDesc() {
		return this.desc;
	}

When insert into category table, hits following error message :


Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 
   You have an error in your SQL syntax; check the manual that corresponds to your 
   MySQL server version for the right syntax to use near 'DESC) 
   values ('CONSUMER', 'CONSUMER COMPANY')' at line 1
   ... 35 more

Solution

In Hibernate, to insert into “keyword” column name, you should enclose it like this ‘[column name]‘.

Hibernate XML mapping file


<hibernate-mapping>
    <class name="com.mkyong.stock.Category" table="category" catalog="mkyongdb">
        ...
        <property name="desc" type="string">
            <column name="[DESC]" not-null="true" />
        </property>
       ...
    </class>
</hibernate-mapping>

Or Hibernate annotation


@Column(name = "[DESC]", nullable = false)
	public String getDesc() {
		return this.desc;
	}

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Richard
10 years ago

Thanks, this was very useful!

patrick
11 years ago

Good day sir, how do you do this in PHP? i’m having trouble myself…
mysql_query(“INSERT INTO items (desc) VALUES (‘$desc’)”);

name
10 years ago
Reply to  patrick

this is not even remotely related to PHP … you’re on the wrong website, this article is about HIBERNATE and JAVA, your column-problems dont apply here