---
title: "Hibernate3.4 不自动创建索引的问题"
author: "roc08"
date: "2014-12-22T11:28:40Z"
tags: []
categories: ["编程语言"]
slug: "hibernate3-4"
draft: false
lastmod: "2014-12-22T11:27:13Z"
id: 2169162
url: "https://roc08.iteye.com/blog/2169162"
---

现在很多小团队都弱化了DBA的角色，有些团队甚至没有DBA，这时数据库文档和索引等的维护就是很大的问题了，关于数据库文档我写了一个maven插件可以基于Hibernate注解的po生成数据库文档
   而对于索引 我看到Hibernate有这个注解，但是加上之后不会自动生成索引，在网上查了很多资料都说的似是而非，有的说可以 有的说不可以，最后找到Hibernate的jira，发现这是个bug 已经修复了，因此我对比了我们正在用的Hibernate3.4版本和3.5的Hibernate生成数据库脚本类的区别，发现Configuration中是生成要创建的数据库 字段 和索引的地方，因此只需修改这个类即可，当然最好是升级到最新版Hibernate，由于我们使用的osgi环境对Hibernate进行了修改，故升级成本太高，暂时只能修改源代码解决，后续会升级到Hibernate最新版本。
Hibernate 3.5版本修复了这个bug

修改文件org.hibernate.cfg. Configuration的generateSchemaUpdateScript方法在1071行
增加
	Iterator subIter = table.getIndexIterator();
	while ( subIter.hasNext() ) {
		final Index index = (Index) subIter.next();
		// Skip if index already exists
	if ( tableInfo != null && StringHelper.isNotEmpty( index.getName() ) ) {
		final IndexMetadata meta = tableInfo.getIndexMetadata( index.getName() );
	if ( meta != null ) {
		continue;
	}
}
script.add(
index.sqlCreateString(dialect,mapping,defaultCatalog,defaultSchema)
);
}