mybatis高階查詢

2022-02-22 17:33:07 字數 2722 閱讀 4450

sqlsession的獲取

sqlsessionfactorybean bean = new sqlsessionfactorybean();

bean.setdatasource(mysqldatasource());

bean.setconfiglocation(new pathmatchingresourcepatternresolver().getresource("classpath:mybatis/mybatis-config.xml"));

bean.settypealiasespackage("com.getword.entity");

sqlsessionfactory = bean.getobject();

假設user和role是一對一關係,中間表為sys_user_role

public class sysuser
select

u.id,

u.username username,

u.userpassword userpassword,

r.id "role.id",

r.rolename "role.rolename"

from sys_user u

inner join sys_user_role ur on u.id=ur.userid

inner join sys_role r on r.id = ur.roleid

where u.id = #

使用resultmap,和第一種方式類似

select

u.id,

u.username username,

u.userpassword userpassword,

r.id roleid,

r.rolename rolename

from sys_user u

inner join sys_user_role ur on u.id=ur.userid

inner join sys_role r on r.id = ur.roleid

where u.id = #

此種方式,對於多表查詢,只會封裝指定的result標籤的字段

select

u.id,

u.username username,

u.userpassword userpassword,

r.id roleid,

r.rolename rolename

from sys_user u

inner join sys_user_role ur on u.id=ur.userid

inner join sys_role r on r.id = ur.roleid

where u.id = #

resultmap可以繼承

select

u.id,

u.username username,

u.userpassword userpassword,

r.id roleid,

r.rolename rolename

from sys_user u

inner join sys_user_role ur on u.id=ur.userid

inner join sys_role r on r.id = ur.roleid

where u.id = #

select

u.id,

u.username username,

u.userpassword userpassword,

r.id roleid

from sys_user u

inner join sys_user_role ur on u.id=ur.userid

inner join sys_role r on r.id = ur.roleid

where u.id = #

簡寫

select

*from sys_user u

inner join sys_user_role ur on u.id=ur.userid

where u.id = #

select

u.id,

u.username username,

u.userpassword userpassword,

r.id roleid,

r.rolename rolename

from sys_user u

inner join sys_user_role ur on u.id=ur.userid

inner join sys_role r on r.id = ur.roleid

where u.id = #

對於id相同的user被歸為乙個user,相當於分組了

MyBatis 高階查詢(二)

一對多對映 在上一節中,我們使用了4種方法實現一對一對映,這一節,一對多對映只有兩種配置方式,都是使用collection標籤進行的 collection集合的巢狀結果查詢 和association類似,集合的巢狀結果查詢就是通過一次sql查詢將所有的結果查詢出來,然後通過配置的結果對映,將資料對映...

MyBatis 高階查詢之多對多查詢(十一)

查詢條件 根據玩家名,查詢遊戲資訊 根據玩家名查詢遊戲 param name 玩家名 return 玩家實體類 public playerentity selectplayerbyname string name 接下來,我分別演示關聯查詢和子查詢方式實現介面方法的對映。關聯查詢方式 現在我們暫時先...

mybatis高階操作

finduserbycondition resultmap usermap parametertype user select from user test username null and username if test user null and if where select findus...