简体   繁体   中英

how to define char(2) column in hibernate hbm.xml?

Hi must modify some hibernate legacy code and I should define a SQL char(2) column (foreign key to a char(2) primary key).

My definition file contains:

    <property
        name="language"
        type="char"
        update="true"
        insert="true"
        column="LANGUAGE"
        length="2"
    />

but hibernate generates:

+---------------------+--------------+------+-----+---------+----------------+
| Field               | Type         | Null | Key | Default | Extra          |
+---------------------+--------------+------+-----+---------+----------------+
(...)
| LANGUAGE            | char(1)      | YES  |     | NULL    |                |    
+---------------------+--------------+------+-----+---------+----------------+

The foreign key table is something like:

+--------------+--------------+------+-----+---------+-------+
| Field        | Type         | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| LANGUAGE     | char(2)      | NO   | PRI | NULL    |       |
(...)
+--------------+--------------+------+-----+---------+-------+

Using:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>3.3.1.GA</version>
    </dependency>

The char type in Hibernate does not map to a String , it maps to a char or Character in Java (see 6.1.1.2 ). It happens to use char(1) as the underlying column type in the table to support this for your DBMS; which by coincidence makes it seem like it's simply ignoring the length (but its reasons are actually unrelated).

You'll have to use string for the type (so it maps to a Java String ), then you'll have to tell it to use char(2) for storage. One option is to explicitly specify sql-type , eg:

<property name="language" type="string" update="true" insert="true">
    <column name="LANGUAGE" sql-type="char(2)"/>
</property>

Or just manually adjust the table afterwards to change it from varchar(2) to char(2) .

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