springboot多對一關系映射


 原文:https://blog.csdn.net/h993438890/article/details/89146483  

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;
    //此處省略getter/setter方法
}
public class Dept {
    private Long id;
    private String dname;
    //...此處省略getter/setter方法
}

第一種:嵌套結果查詢

在usermapper.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="com.example.springboot.mapper.UserMapper">
 4     <resultMap id="queAllMap" type="com.example.springboot.domain.User">
 5         <id property="id" column="id"/>
 6         <result property="username" column="username"/>
 7         <result property="pwd" column="pwd"/>
 8         <association property="dept" column="did" javaType="com.example.springboot.domain.Dept">
 9             <id property="id" column="d_id"/><!--根據sql查詢出列,這里為了和t_user表的主鍵id區分,取了別名,如果不區分,結果會出錯-->
10             <result property="dname" column="dname"/>
11         </association>
12     </resultMap>
13     <select id="queAll" resultMap="queAllMap">
14         select u.*,d.id d_id ,d.dname from t_user u left join t_dept d on u.did=d.id
15     </select>
16 </mapper>

在對應的UserMapper.java中代碼

@Mapper
public interface UserMapper {
    //@Select("select * from t_user")
    List<User> queAll();
}

第二種:嵌套查詢

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="com.example.springboot.mapper.UserMapper">
 4     <select id="queAll" resultMap="queAllMap">
 5         select u.*,d.id ,d.dname from t_user u left join t_dept d on u.did=d.id
 6     </select>
 7     <resultMap id="queAllMap" type="com.example.springboot.domain.User">
 8         <id property="id" column="id"/>
 9         <result property="username" column="username"/>
10         <result property="pwd" column="pwd"/>
11         <association property="dept" column="did" select="getDeptById"/>
12     </resultMap>
13     <select id="getDeptById" parameterType="Long" resultType="com.example.springboot.domain.Dept">
14         select * from t_dept where id=#{id}
15     </select>
16 </mapper>

還要在DeptMapper.java中添加一個方法

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

對assacation標簽的屬性進行解釋一下

  •   property      對象屬性的名稱
  •   javaType     對象屬性的類型
  •   column        所對應的外鍵字段名稱
  •   select          使用另一個查詢封裝的結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM