Mybatis表之间的映射
1.一对一
<!--对account对象的封装,每个account对象中有一个User对象作为属性--> <resultMap id="accountUserMap" type="com.itheima.domain.Account"> <!--这里的aid是sql语句查询时使用的别名,同时这里的id标签和下面的id标签应该都可以换成result标签--> <id property="id" column="aid"></id> <result property="uid" column="uid"></result> <result property="money" column="money"></result> <!--配置一对一关系,对User对象的封装 assocaiation中的column好像可以不要--> <association property="user" column="uid" javaType="com.itheima.domain.User"> <id property="id" column="id"></id> <result property="username" column="username"></result> <result property="birthday" column="birthday"></result> <result property="sex" column="sex"></result> <result property="address" column="address"></result> </association> </resultMap> <!--id为接口中的方法名--> <select id="findAll" resultMap="accountUserMap"> select u.*,a.id aid,a.uid,a.money from user u,account a where u.id=a.uid; </select>
2.一对多
<resultMap id="UserMap" type="com.itheima.domain.User"> <id property="id" column="id"></id> <result property="username" column="username"></result> <result property="birthday" column="birthday"></result> <result property="sex" column="sex"></result> <result property="address" column="address"></result> <collection property="accounts" ofType="com.itheima.domain.Account"> <!--列名aid要与查询语句中的别名对应--> <id property="id" column="aid"></id> <result property="uid" column="uid"></result> <result property="money" column="money"></result> </collection> </resultMap> <!--id为接口中的方法名,,注意外连接用on--> <select id="findAll" resultMap="UserMap"> select u.*,a.id aid,a.uid,a.money from user u left outer join account a on u.id=a.uid; </select>
3.多对多
个人觉得多对多的配置和一对多的配置一样,只是SQL语句的编写不同,SQL语句查出来的数据的列名(column)和实体类的属性(property)一一对应就行了。
<!--type为返回值类型,也可以说是封装的类型,是一个实体类--> <resultMap id="roleMap" type="com.itheima.domain.Role"> <!--配置该实体类的基本属性--> <id property="id" column="rid"></id> <result property="role_name" column="role_name"></result> <result property="role_desc" column="role_desc"></result> <!--配置实体类的关联属性,ofType是所关联的属性的类型--> <collection property="users" ofType="com.itheima.domain.User"> <id property="id" column="id"></id> <result property="username" column="username"></result> <result property="birthday" column="birthday"></result> <result property="sex" column="sex"></result> <result property="address" column="address"></result> </collection> </resultMap> <select id="findAll" resultMap="roleMap"> select u.*,r.id rid,r.role_name,r.role_desc from role r left join user_role ur on r.id=ur.rid left join user u on u.id=ur.uid; </select>
property