简单介绍:用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"),看着比较生疏,其实和下边的图一个道理。