数据库查询结果、Ibatis的ResultMap与JavaBean的对应关系

来源:互联网 发布:windows系统 编辑:程序博客网 时间:2024/06/03 16:01

对数据库的Select查询结果字段多少、名称、类型先与Ibatis的ResultMap对应是否一致,然后Ibatis的ResultMap再与JavaBean对应是否一致。Ibatis的ResultMap是核心。
1、Select查询结果的字段个数多于Ibatis的ResultMap中定义的字段,不会出错
2、Select查询结果的字段个数少于Ibatis的ResultMap中定义的字段,会出错。
测试:ResultMap文件名为SqlMapStudent.xml,查询结果ResultMap的ID为student.StudentRecordResult。JavaBean为com.cea.callcenter.bean.Student。Select查询结果里没有字段stuEmail,StudentRecordResult里定义了字段stuEmail
结果:运行产生异常,异常信息提示在SqlMapStudent.xml的payment.PayRecordResult里有非法字段stuEmail

org.springframework.jdbc.BadSqlGrammarException: SqlMapClient operation; bad SQL grammar []; nested exception is com.ibatis.common.jdbc.exception.NestedSQLException:   --- The error occurred in daoConfig/SqlMapStudent.xml.  --- The error occurred while applying a result map.  --- Check the payment.PayRecordResult.  --- Check the result mapping for the 'stuEmail' property.  --- Cause: java.sql.SQLException: Invalid column name

3、Ibatis的ResultMap中定义的字段多于JavaBean中定义的字段,会出错。
测试:ResultMap文件名为SqlMapStudent.xml,查询结果ResultMap的ID为student.StudentRecordResult。JavaBean为com.cea.callcenter.bean.Student。StudentRecordResult里定义了字段stuEmail,com.cea.callcenter.bean.Student没有字段stuEmail
结果:运行产生异常,异常信息提示在类Student里没有可写的属性stuEmail

org.springframework.jdbc.UncategorizedSQLException: SqlMapClient operation; uncategorized SQLException for SQL []; SQL state [null]; error code [0];   --- The error occurred in daoConfig/SqlMapStudent.xml.  --- The error occurred while applying a result map.  --- Check the student.StudentRecordResult.  --- The error happened while setting a property on the result object.  --- Cause: com.ibatis.common.beans.ProbeException: There is no WRITEABLE property named 'stuEmail' in class 'com.cea.callcenter.bean.Student'; nested exception is com.ibatis.common.jdbc.exception.NestedSQLException:   


3、Ibatis的ResultMap中定义的字段少于JavaBean中定义的字段,不会出错。JavaBean中多的那个字段结果为默认值null

所以对于字段个数,按以下原则就不会出错
Select查询结果的字段个数>=Ibatis的ResultMap中定义的字段个数<=JavaBean中定义的字段个数

4、如果把resultMap换成resultClass,select查询结果的字段个数多于或少于resultClass都不会出现异常。

<select id="getAllInsuranceRecordByBean" resultMap="student.StudentRecordResult" parameterClass="com.cea.callcenter.bean.Student">select stuName from tbl_student</select>


换为如下

<select id="getAllInsuranceRecordByBean" resultClass="com.cea.callcenter.bean.Student" parameterClass="com.cea.callcenter.bean.Student">select stuName from tbl_student</select>


1、Select查询结果的字段个数多于resultClass中定义的字段,resultClass中没有这个字段,也不报错
2、Select查询结果的字段个数少于resultClass中定义的字段,resultClass中多的这个字段值为null


看来用resultClass比resultMap更方便,还不出错




0 0
原创粉丝点击