---
title: "No Dialect mapping for JDBC type: 3"
author: "hypgr"
date: "2008-10-29T19:12:47Z"
tags: []
slug: "no-dialect-mapping-for-jdbc-type-3"
draft: false
lastmod: "2008-10-29T19:12:47Z"
id: 259755
url: "https://hypgr.iteye.com/blog/259755"
---

我要从数据库中Select sum(price) from talbe获取一些统计数据作为参数传给JasperReport生成报表。为了达到数据本来应该有的精度，所以在数据库中price的数据类型为decimal(20,2)。由于只是简单地从数据库把price,sum出来并不需要进行更进一步的复杂数据处理，所以在实现中我并没有为table写相应该的Pojo和hbm文件。所以在Dao层，我使用Hibernate运行SQL语句将数据检索出来。代码如下：

  BigDecimal totalPrice = (BigDecimal) this .getHibernateTemplate().execute( new  HibernateCallback()  {

         public  Object doInHibernate(Session session)  throws  HibernateException, SQLException   {  
            MonthCheckTable monthCheckTable = new  MonthCheckTable();  
              
            List rs = session.createSQLQuery( " select sum(price) from table " ).list();  
            Number totalPrice  =  (Number)rs.get( 0 );  
             if (totalPrice == null ) totalPrice = new  BigDecimal( 0.0 );  
                          
             return   new  BigDecimal(totalPrice.toString());  
        }   
    } );

运行的时候就出现了Maping Excetion,异常栈如下：

org.springframework.orm.hibernate3.HibernateSystemException: No Dialect mapping for JDBC type: 3; nested exception is org.hibernate.MappingException: No Dialect mapping for JDBC type: 3  
Caused by: org.hibernate.MappingException: No Dialect mapping for JDBC type: 3 

出现这个原因是说服务器端的数据类型并不能和Java的BigDecimal数据类型成功映射。  
推想只要在Hibernate里把本对应的数据类型成功映射起来就可以成功执行了。  
解决案如下：  
1、新建一个MySQLServerDialect extends org.hibernate.dialect.SQLServerDialect 并在里面补充注册新的类型映射。如下：

public class MySQLServerDialect extends SQLServerDialect{  
    public MySQLServerDialect() {  
        super();  
        registerHibernateType(Types.DECIMAL, Hibernate.BIG\_DECIMAL.getName());  
    }  
}

2、把Hibernate里的Dialect改成我们第一步新建的新的Dialect

&lt;prop key="hibernate.dialect"&gt;com.gdnfha.atcs.common.MySQLServerDialect&lt;/prop&gt;

经过这两步这后就可以正常使用SqlQuery拿到Sql Server 2005里的decimal类型了。

在SQLServerDialect里的registerHibernateType函数，更详细的用法请看：

[http://www.hibernate.org/hib\_docs/v3/api/org/hibernate/dialect/Dialect.html#registerHibernateType(int,%20int,%20java.lang.String](http://www.hibernate.org/hib_docs/v3/api/org/hibernate/dialect/Dialect.html#registerHibernateType%28int,%20int,%20java.lang.String))