mybatis定义
MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
mybatis优点
减少dao层代码,将java实现跟sql分离,方便管理。
减轻了程序员书写维护代码的成本,精力。
resultMap的使用
mybatis中映射结果的返回方式,分为resultType和resultMap,二者不能同时存在。
resultType简便好用
但是resultMap作为mybatis的神兵利器,在数据库中表格的字段名与java中类的属性名不一致的时候,我们就要使用resultMap的强大功能。
用一对一,一对多举例:
一个用户表,一个用户的账单表(一个用户有多个账单),一个用户信息表
方案一:联表查询join(一对多映射集合,一对一映射对象),注意字段冲突
<!--这里的id="ss",是唯一标识符,方便别其他select引用-->
<!--这里的type是返回对象的属性-->
<resultMap id="ss" type="entity.Student">
<!--子标签分两种:主键,非主键-->
<!--id代表主键-->
<!--result代表非主键-->
<!--column指定字段名,property指定属性名-->
<id column="id" property="id"/>
<result column="user_name" property="userName"/>
<result column="password" property="password"/>
<result column="gender" property="gender"/>
<result column="age" property="age"/>
<!--collection映射集合,ofType指定bills集合中的对象类型-->
<collection property="bills" ofType="entity.Bill">
<id column="bill_id" property="billId"/>
<result column="user_id" property="userId"/>
<result column="bill_name" property="billName"/>
<result column="money" property="money"/>
</collection>
<!--association映射对象,javaType指定对象的类型-->
<association property="userInfo" javaType="entity.UserInfo">
<id column="user_info_id" property="id"/>
<result column="user_id" property="userId"/>
<result column="hobby" property="hobby"/>
<result column="company" property="company"/>
</association>
</resultMap>
<select id="selectAll" resultMap="userObj">
SELECT * from `user` LEFT JOIN bill ON `user`.id=bill.user_id
</select>
方案二:套用子查询,可以解决字段冲突
<!-- 方案二:套用子查询 主查询resultMap -->
<resultMap id="userObj" type="obj.UserObj">
<id column="id" property="id"></id>
<result column="user_name" property="user_name"></result>
<result column="password" property="password"></result>
<result column="gender" property="gender"></result>
<result column="age" property="age"></result>
<!--select 子查询的id名,column=""当前表传入子查询中的参数值-->
<collection property="bills" select="selectBillsByUserId" column="id"/>
<!--同理对象类型association也可以这么干-->
</resultMap>
<!--sql语句-->
<select id="selectAll" resultMap="userObj">
SELECT *FROM `user`;
</select>
<select id="selectBillsByUserId" resultMap="billMap">
SELECT * FROM bill WHERE user_id=#{id}
</select>
<!--子查询resultmap-->
<resultMap id="billMap" type="obj.Bill">
<id property="id" column="bill_id"/>
<result property="billName" column="bill_name"/>
<result property="money" column="money"/>
<result property="userId" column="user_id"/>
</resultMap>