簡單介紹:用ssm框架已經有很長時間了,但是似乎從來都沒有對於查詢單個對象,存在問題的,好像也就是那回事,寫完sql就查出來了,也從來都沒有認真的想過,為什么會這樣,為什么要設置結果集類型
代碼:
//service層代碼
ContractVo contractObj = (ContractVo)dao.findForObject("ContractMapper.getContractObj",contractId);
//Model對象
@Alias("ContractVo")
@Getter
@Setter
public class Contract {
private String contractId;
private String contractNumber;
private String contractType;
private String contractStatus;
private String startTime;
private String endTime;
private String regularAgency;
}
//mapper里的sql相關
<resultMap id="ContractVoResultMap" type="ContractVo">
<result column="contract_id" property="contractId" jdbcType="CHAR"/>
<result column="contract_number" property="contractNumber" jdbcType="VARCHAR"/>
<result column="contract_type" property="contractType" jdbcType="VARCHAR"/>
<result column="contract_status" property="contractStatus" jdbcType="VARCHAR"/>
<result column="start_time" property="startTime" jdbcType="Date"/>
<result column="end_time" property="endTime" jdbcType="Date"/>
<result column="regular_agency" property="regularAgency" jdbcType="VARCHAR"/>
</resultMap>
<select id="getContractObj" parameterType="String" resultMap="ContractVoResultMap">
select
<include refid="FieldOne"></include>
from
<include refid="tableName"></include>
where contract_id = #{contractId}
</select>
<!--字段-->
<sql id="FieldOne">
contract_id,
contract_number,
contract_type,
contract_status,
start_time,
end_time,
regular_agency
</sql>
<!--表名 -->
<sql id="tableName">
t_contract
</sql>
說明:為什么要設置resultMap ,是為了指定sql輸出結果所映射的java對象類型,這里select指定resultType表示單條記錄所映射成的java對象,也許你會覺得在mapper 文件里配置映射pojo (resultMap-->type="ContractVo"),看着比較生疏,其實和下邊的圖一個道理。