spring boot + mybatis多对一关系映射

spring boot项目的创建省略
创建两张表
t_user 字段 主键id,username(varchar) , pwd(varchar) ,did(外键)

t_dept 字段 主键id,dname(varchar)

建立两个实体类User ,Dept。提供相应的getter和setter方法

public class User {
    private Integer id;
    private String username;
    private String pwd;
    //多对一
    private Dept dept;
    }
public class Dept {
    private Long id;
    private String dname;
    }

第一种:嵌套结果查询
在usermapper.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="com.example.springboot.mapper.UserMapper">
    <resultMap id="queAllMap" type="com.example.springboot.domain.User">
       <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="pwd" column="pwd"/>
        <association property="dept" column="did" javaType="com.example.springboot.domain.Dept">
          <id property="id" column="d_id"/>
           <result property="dname" column="dname"/>
        </association>
    </resultMap>
   <select id="queAll" resultMap="queAllMap">
        select u.*,d.id d_id ,d.dname from t_user u left join t_dept d on u.did=d.id
   </select>
</mapper>

在对应的UserMapper.java中代码

@Mapper
public interface UserMapper {

    //@Select("select * from t_user")
    List<User> queAll();
    
    }

第二种:嵌套查询

<?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="com.example.springboot.mapper.UserMapper">
   <select id="queAll" resultMap="queAllMap">
        select u.*,d.id ,d.dname from t_user u left join t_dept d on u.did=d.id
   </select>
    <resultMap id="queAllMap" type="com.example.springboot.domain.User">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="pwd" column="pwd"/>
        <association property="dept" column="did" select="getDeptById"/>
    </resultMap>
  <select id="getDeptById" parameterType="Long" resultType="com.example.springboot.domain.Dept">
      select * from t_dept where id=#{id}
  </select>
</mapper>

还要在DeptMapper.java中添加一个方法

@Mapper
public interface DeptMapper {

    @Select("select * from t_dept where id=#{id}")
    Dept getDeptById(Long id);
}

猜你喜欢

转载自blog.csdn.net/h993438890/article/details/89146483
今日推荐