1. 程式人生 > >mybatis使用generator自動生成程式碼時的型別轉換

mybatis使用generator自動生成程式碼時的型別轉換

使用mybatis的generator自動生成程式碼,但是oracle資料庫中number(6,2)總是自動轉成BigDecimal,我想要轉成的是float型別

這樣就寫了一個型別轉換器,需要繼承JavaTypeResolver介面

然後在mybaties配置檔案generatorConfig.xml中型別轉換配置位置新增上即可

<javaTypeResolver type="com.generator.MyJavaTypeResolver">
	<property name="forceBigDecimals" value="false" />											<!-- 型別解析器 -->
</javaTypeResolver>
型別轉換器MyJavaTypeResolver主要程式碼
public FullyQualifiedJavaType calculateJavaType(
			IntrospectedColumn introspectedColumn) {
		// TODO Auto-generated method stub
		 FullyQualifiedJavaType answer;
	        JdbcTypeInformation jdbcTypeInformation = typeMap
	                .get(introspectedColumn.getJdbcType());

	        if (jdbcTypeInformation == null) {
	            switch (introspectedColumn.getJdbcType()) {
	            case Types.DECIMAL:
	            case Types.NUMERIC:
	            	if(introspectedColumn.getScale() > 0)
	            	{//如果包含小數點則轉換成float
	            		answer = new FullyQualifiedJavaType(Float.class.getName());
	            	}else{
	            		if ( introspectedColumn.getLength() > 18
	            				|| forceBigDecimals) {
	            			answer = new FullyQualifiedJavaType(BigDecimal.class
	            					.getName());
	            		} else if (introspectedColumn.getLength() > 9) {
	            			answer = new FullyQualifiedJavaType(Long.class.getName());
	            		} else if (introspectedColumn.getLength() > 4) {
	            			answer = new FullyQualifiedJavaType(Integer.class.getName());
	            		} else {
	            			answer = new FullyQualifiedJavaType(Short.class.getName());
	            		}
	            	}
	                break;

	            default:
	                answer = null;
	                break;
	            }
	        } else {
	            answer = jdbcTypeInformation.getFullyQualifiedJavaType();
	        }

	        return answer;
	}