mybatis xml表关系映射配置
一对一:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.mybatis.dao.OrderMapper"> // 命名空间要与OrderMapper的全路径名一致
//当前表对应的实体类
<resultMap id="orderMap" type="order">
<result column="id" property="id"></result>
<result column="money" property="money"></result>
<result column="orderTime" property="orderTime"></result>
//一对一: 使用association配置
<association property="user" javaType="user">
<result column="userId" property="id"></result>
<result column="username" property="username"></result>
</association>
</resultMap>
<select id="findAll" resultMap="orderMap">
SELECT * FROM tb_order o, tb_user u WHERE o.userId = u.id;
</select>
</mapper>
实体类:将对应的实体类直接作为属性配置上即可:
public class Order {
private int id; // 订单id
private int money; // 订单金额
private Date orderTime; // 下单时间
//一对一实体类配置××××**********
private User user; // 下单用户
}
一对多:
xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.mybatis.dao.UserMapper">
//当前类映射文件
<resultMap id="userMap" type="user">
<result column="id" property="id"></result>
<result column="username" property="username"></result>
//一对多对应类映射文件配置
<collection property="orderList" ofType="order">
<id column="oid" property="id"></id>
<result column="money" property="money"></result>
<result column="orderTime" property="orderTime"></result>
</collection>
</resultMap>
<select id="findUserWithOrders" resultMap="userMap">
select *,o.id oid from tb_user u, tb_order o where u.id = o.userId;
</select>
</mapper>
实体类:将对应的实体类作为list属性<类>配置即可
public class User {
private int id; // 用户id
private int username; // 用户名
//一对多实体类映射×××××××××××××××××××××××××××××××××××××
private List<Order> orderList; // 订单列表
private List<Role> roleList; // 角色列表
}
多对多:
xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.mybatis.dao.UserMapper">
<resultMap id="userRoleMap" type="user">
<result column="id" property="id"></result>
<result column="username" property="username"></result>
<collection property="roleList" ofType="role">
<id column="roleId" property="id"></id>
<result column="name" property="name"></result>
</collection>
</resultMap>
<select id="findUserWithRoles" resultMap="userRoleMap">
SELECT * ,r.id roleId FROM tb_user u, tb_role r ,tb_user_role ur WHERE u.id = ur.userId AND r.id = ur.roleId;
</select>
</mapper>
多对多配置是一样的,只是需要修改的是两边的类都需要配置对方的list<类>