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


对数据库的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更方便,还不出错




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值