Hibernate修改命名策略

解決思路:html

一、解決關鍵字問題;java

二、解決大小寫敏感的問題。spring

首先解決第一個問題,這裏有幾種方式session

(1)將表名或字段名用方括號([])括起來app

XMLide

<property name="context" type="string" > 
<column name="[CONTEXT]" length="255" not-null="true" /> 
</property>

註解spring-boot

@Column(name = "[CONTEXT]", nullable = false)   
private String context;

(2)將表名或字段名用雙引號(")括起來ui

XML.net

<property name="context" type="string" > 
<column name='"CONTEXT"' length="255" not-null="true" />
</property>

註解hibernate

@Column(name = "\"CONTEXT\"", nullable = false)   
private String context;

    解決了第一個問題以後咱們再來解決第二個問題,因爲Hibernate默認講全部表名、字段名都轉換成小寫字母,因此通過轉換以後的SQL語句相似於SELECT obj."context" FROM obj;這樣的SQL在Oracle中運行也有問題,而SELECT OBJ."CONTEXT" FROM OBJ;這樣的SQL運行就問題,因此就須要解決Hibernate大小寫的問題,Hibernate控制表名和字段名大小寫的配置類爲org.hibernate.cfg.ImprovedNamingStrategy,因此咱們如今要重寫Hibernate的命名策略。

    總共須要兩個步驟:

(1)寫一個替代Hibernate默認命名規則類

package com.xjj.framework.hibernate.cfg;

import java.io.Serializable;
import java.util.Locale;

import org.hibernate.AssertionFailure;
import org.hibernate.cfg.ImprovedNamingStrategy;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.internal.util.StringHelper;

public class DMNamingStrategy extends ImprovedNamingStrategy implements
		NamingStrategy, Serializable {

	/**
	 * A convenient singleton instance
	 */
	public static final NamingStrategy INSTANCE = new DMNamingStrategy();

	/**
	 * Return the unqualified class name, mixed case converted to
	 * underscores
	 */
	@Override
	public String classToTableName(String className) {
		return addUnderscores( StringHelper.unqualify(className) );
	}
	/**
	 * Return the full property path with underscore seperators, mixed
	 * case converted to underscores
	 */
	@Override
	public String propertyToColumnName(String propertyName) {
		return addUnderscores( StringHelper.unqualify(propertyName) );
	}
	/**
	 * Convert mixed case to underscores
	 */
	@Override
	public String tableName(String tableName) {
		return addUnderscores(tableName);
	}
	/**
	 * Convert mixed case to underscores
	 */
	@Override
	public String columnName(String columnName) {
		return addUnderscores(columnName);
	}

	protected static String addUnderscores(String name) {
		StringBuilder buf = new StringBuilder( name.replace('.', '_') );
		for (int i=1; i<buf.length()-1; i++) {
			if (
				Character.isLowerCase( buf.charAt(i-1) ) &&
				Character.isUpperCase( buf.charAt(i) ) &&
				Character.isLowerCase( buf.charAt(i+1) )
			) {
				buf.insert(i++, '_');
			}
		}
		return buf.toString().toUpperCase(Locale.ROOT);
	}

	@Override
	public String collectionTableName(
			String ownerEntity, String ownerEntityTable, String associatedEntity, String associatedEntityTable,
			String propertyName
	) {
		return tableName( ownerEntityTable + '_' + propertyToColumnName(propertyName) );
	}

	/**
	 * Return the argument
	 */
	@Override
	public String joinKeyColumnName(String joinedColumn, String joinedTable) {
		return columnName( joinedColumn );
	}

	/**
	 * Return the property name or propertyTableName
	 */
	@Override
	public String foreignKeyColumnName(
			String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName
	) {
		String header = propertyName != null ? StringHelper.unqualify( propertyName ) : propertyTableName;
		if (header == null) throw new AssertionFailure("NamingStrategy not properly filled");
		return columnName( header ); //+ "_" + referencedColumnName not used for backward compatibility
	}

	/**
	 * Return the column name or the unqualified property name
	 */
	@Override
	public String logicalColumnName(String columnName, String propertyName) {
		return StringHelper.isNotEmpty( columnName ) ? columnName : StringHelper.unqualify( propertyName );
	}

	/**
	 * Returns either the table name if explicit or
	 * if there is an associated table, the concatenation of owner entity table and associated table
	 * otherwise the concatenation of owner entity table and the unqualified property name
	 */
	@Override
	public String logicalCollectionTableName(String tableName,
											 String ownerEntityTable, String associatedEntityTable, String propertyName
	) {
		if ( tableName != null ) {
			return tableName;
		}
		else {
			//use of a stringbuffer to workaround a JDK bug
			return new StringBuffer(ownerEntityTable).append("_")
					.append(
						associatedEntityTable != null ?
						associatedEntityTable :
						StringHelper.unqualify( propertyName )
					).toString();
		}
	}
	/**
	 * Return the column name if explicit or the concatenation of the property name and the referenced column
	 */
	@Override
	public String logicalCollectionColumnName(String columnName, String propertyName, String referencedColumn) {
		return StringHelper.isNotEmpty( columnName ) ?
				columnName :
				StringHelper.unqualify( propertyName ) + "_" + referencedColumn;
	}
}

基本上是將ImprovedNamingStrategy類拷貝過來並修改addUnderscores方法的返回值爲toUpperCase便可。

(2)將命名策略配置到Hibernate的SessionFactory初始化配置上

因爲咱們公司是使用spring-boot來進行開發的,因此這裏給出spring-boot的配置,是通過驗證的,XML配置還沒有通過驗證,配錯了我不背鍋哦。

spring-boot 1.3.8版本配置

spring.jpa.hibernate.naming_strategy: com.xjj.framework.hibernate.cfg.DMNamingStrategy

spring-boot 1.4.0以上版本的配置

spring.jpa.hibernate.naming.physical-strategy=com.xjj.framework.hibernate.cfg.DMNamingStrategy

詳見:http://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/reference/html/howto-data-access.html#howto-configure-jpa-properties

XML方式配置

<bean id="sessionFactory" 
           class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
       <property name="dataSource" ref="dataSource" />
       <property name="namingStrategy" ref="namingStrategy" />
</bean>

以上就是解決這個問題的方案了。

參考:

一、http://blog.csdn.net/xt0916020331/article/details/49905949

二、https://my.oschina.net/moks/blog/292740

相關文章
相關標籤/搜索