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;
	}

3 comments on “Hibernate – Unable to insert if column named is keyword, such as DESC

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

    Reply
    1. 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

      Reply

Leave a Comment

Your email address will not be published. Required fields are marked *