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 the Author

author image
mkyong
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

avatar
3 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
nameRichardpatrickHibernate Tutorials Recent comment authors
newest oldest most voted
Richard
Guest
Richard

Thanks, this was very useful!

patrick
Guest
patrick

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

name
Guest
name

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

trackback
Hibernate Tutorials

[…] Unable to insert if column named is keyword, such as DESC […]