mybatis多對多的問題彙總

1.只顯示地址,不顯示內容:

結果顯示

@Testpublic void searchUserRole(){List<User>list=userDao.searchUserRole();for(User u:list){System.out.println(u);System.out.println("\t\t"+u.getRoles());}}

 查看代碼發現沒有問題,難道是實體類的原因?

後來發現實體類少了重寫ToString()方法:

@Overridepublic String toString() {return "Role{" +"id=" + id +", name='" + name + '\'' +", desc='" + desc + '\'' +", users=" + users +'}';}

但是還是有問題,如下,名字重複:

原因在於user表和role表有字段名重複:

<resultMap id="userRoleMap" type="com.aaa.entity.User"><!--主鍵字段對應的屬性;property:實體類屬性;column:數據庫列名--><id property="id" column="id"></id><!--非主鍵字段--><result property="name" column="name"></result><result property="birth" column="birth"></result><result property="gender" column="gender"></result><result property="address" column="address"></result><!--建立了一對多關係之後,需要繼續--><collection property="roles" ofType="role"><id property="id" column="id"></id><result property="name" column="name"></result><result property="desc" column="desc"></result></collection></resultMap>

 原來的sql語句:

SELECT u.*,r.*
FROM user u left JOIN user_role ur on u.id=ur.uid
left JOIN role r on ur.rid=r.id

使用別名之後:

<select id="searchUserRole" resultMap="userRoleMap">SELECT u.*,r.id rid,r.name rname,r.descFROM user u left JOIN user_role ur on u.id=ur.uidleft JOIN role r on ur.rid=r.id</select>

 

再看執行效果:

最終結果正常!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章