---
title: "Hibernate对应MySQL的Text字段"
author: "meiping"
date: "2011-03-04T23:34:34Z"
tags: [".net", "Hibernate", "MySQL", "SQL", "XML"]
categories: ["编程语言"]
slug: "hibernate-mysql-text"
draft: false
lastmod: "2011-03-04T23:34:34Z"
id: 941290
url: "https://meiping.iteye.com/blog/941290"
---

Hibernate3.6.1，MySQL5InnoDBDialect

1. 如果hbm文件中property元素的type属性是string，则当不指定column中的length属性时，ddl中默认为varchar(255)。由于varchar(x)中x是与字符集有关系的，最多也就是65535，当指定的length超过65535时，hibernate知道肯定是不能用varchar了，所以自动选择用longtext，在小于等于65535的范围内，hibernate如实生成varchar(length)形式的ddl，能不能执行就看MySQL的了；
2. 如果hbm文件中property元素的type属性是text，则ddl中直接使用longtext；
3. 可以使用column的sql-type属性来明确指定类型，这样就可以使用MySQL中的tinytext和text了，当然这就有可能破坏hbm的通用性了

```
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2011-3-4 22:32:34 by Hibernate Tools 3.3.0.GA -->
<hibernate-mapping>
	<class name="com.wsd.itil.hibernate.TBusiness" table="t_business" catalog="db_issue">
		<id name="id" type="java.lang.Integer">
			<column name="id" />
			<generator class="identity" />
		</id>
		<property name="c1" type="string">
			<column name="c1" not-null="true" default="''" />
		</property>
		<property name="c2" type="string">
			<column name="c2" length="21327" not-null="true" default="''" />
		</property>
		<property name="c3" type="string">
			<column name="c3" length="65536" not-null="true" />
		</property>
		<property name="c4" type="text">
			<column name="c4" not-null="true" />
		</property>
		<property name="c5" type="text">
			<column name="c5" sql-type="text" not-null="true" />
		</property>
	</class>
</hibernate-mapping>
```

 

```
CREATE TABLE `t_business` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `c1` varchar(255) NOT NULL DEFAULT '',
 `c2` varchar(21327) NOT NULL DEFAULT '',
 `c3` longtext NOT NULL,
 `c4` longtext NOT NULL,
 `c5` text NOT NULL,
 PRIMARY KEY (`id`)
)
```