今天搞了一下SpringBoot整合Mybatis,順便突然想聯系下好久不用的一對多,多對多等。
這裡就說一下一對多吧,如.一個班級中,一個老師對應多個學生,那麼在java中就是老師的實體類中包含了一個List<Student>
多對一,一樣就是反過來。
多對多就是多個老師對應多個學生,最好的解決多對多方法就是建立一個第三方表。這裡就不詳細說明了。
步入正題
在做一對多查詢的時候,查詢一個部門下多個員工的時候,每次查詢出來都是一條,和預期想的不一樣。
隻能查詢出一條的xml(錯誤的,因為兩個ID造成了混淆)
<resultMap id="map" type="com.hbsi.springbootmybatis.bean.Department">
<id property="id" column="id"/>
<result property="departmentName" column="departmentName"/>
<collection property="employee" column="employee" ofType="com.hbsi.springbootmybatis.bean.Employee">
<id property="id" column="id"/>
<result property="lastName" column="lastName"/>
<result property="gender" column="gender"/>
<result property="email" column="email"/>
<result property="dId" column="d_id"/>
</collection>
</resultMap>
<select id="listEmployee" resultMap="map">
SELECT d.*,e.* from department d ,employee e where d.id=e.d_id and d.id=#{id}
</select>
顯示結果(錯誤的顯示)
這明顯是不對的,因為我的表中的員工有很多資料。
最後發現,兩個主鍵的ID相同了,造成了混淆,然後就修改了一個主鍵id,修改成了一個其他的别名
修改後
<resultMap id="map" type="com.hbsi.springbootmybatis.bean.Department">
<id property="id" column="id"/>
<result property="departmentName" column="departmentName"/>
<collection property="employee" column="employee" ofType="com.hbsi.springbootmybatis.bean.Employee">
<id property="id" column="emp_id"/> <!--修改id别名為emp_id -->
<result property="lastName" column="lastName"/>
<result property="gender" column="gender"/>
<result property="email" column="email"/>
<result property="dId" column="d_id"/>
</collection>
</resultMap>
<select id="listEmployee" resultMap="map">
SELECT d.*,e.* from department d ,employee e where d.id=e.d_id and d.id=#{id}
</select>
修改别名後運作效果
到這裡其實已經解決的差不多了,然後發現每個裡面的id的值為null,原因是因為我們在mapper修改了ID的别名
<id property="id" column="emp_id"/>導緻與資料庫映射對應不上...那麼我們可以把我們資料庫中的表中id修改成emp_id
這樣就和mapper的xml檔案對應上了
這樣的話再次運作
現在已經全部正常顯示...
後記
出現這種錯誤一般都是在自己測試的時候随意寫ID,在工作中使用的時候一般不會出現這種問題,因為每個表肯定id和字段不會設定重複的。