Mybatis基于注解實現(xiàn)多表查詢功能
對應(yīng)的四種數(shù)據(jù)庫表關(guān)系中存在四種關(guān)系:一對多,多對應(yīng),一對一,多對多。在前文中已經(jīng)實現(xiàn)了xml配置方式實現(xiàn)表關(guān)系的查詢,本文記錄一下Mybatis怎么通過注解實現(xiàn)多表的查詢,算是一個知識的補(bǔ)充。
同樣的先介紹一下Demo的情況:存在兩個實體類用戶類和賬戶類,用戶類可能存在多個賬戶,即一對多的表關(guān)系。每個賬戶只能屬于一個用戶,即一對一或者多對一關(guān)系。我們最后實現(xiàn)兩個方法,第一個實現(xiàn)查詢所有用戶信息并同時查詢出每個用戶的賬戶信息,第二個實現(xiàn)查詢所有的賬戶信息并且同時查詢出其所屬的用戶信息。
1.項目結(jié)構(gòu)

2.領(lǐng)域類
public class Account implements Serializable{
private Integer id;
private Integer uid;
private double money;
private User user; //加入所屬用戶的屬性
省略get 和set 方法.............................
}
public class User implements Serializable{
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
private List<Account> accounts;
省略get 和set 方法.............................
}
在User中因為一個用戶有多個賬戶所以添加Account的列表,在Account中因為一個賬戶只能屬于一個User,所以添加User的對象?!?/p>
3.Dao層
public interface AccountDao {
/**
*查詢所有賬戶并同時查詢出所屬賬戶信息
*/
@Select("select * from account")
@Results(id = "accountMap",value = {
@Result(id = true,property = "id",column = "id"),
@Result(property = "uid",column = "uid"),
@Result(property = "money",column = "money"),
//配置用戶查詢的方式 column代表的傳入的字段,一對一查詢用one select 代表使用的方法的全限定名, fetchType表示查詢的方式為立即加載還是懶加載
@Result(property = "user",column = "uid",one = @One(select = "com.example.dao.UserDao.findById",fetchType = FetchType.EAGER))
})
List<Account> findAll();
/**
* 根據(jù)用戶ID查詢所有賬戶
* @param id
* @return
*/
@Select("select * from account where uid = #{id}")
List<Account> findAccountByUid(Integer id);
}
public interface UserDao {
/**
* 查找所有用戶
* @return
*/
@Select("select * from User")
@Results(id = "userMap",value = {@Result(id = true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "birthday",property = "userBirthday"),
@Result(column = "sex",property = "userSex"),
@Result(column = "address",property = "userAddress"),
@Result(column = "id",property = "accounts",many = @Many(select = "com.example.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY))
})
List<User> findAll();
/**
* 保存用戶
* @param user
*/
@Insert("insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})")
void saveUser(User user);
/**
* 更新用戶
* @param user
*/
@Update("update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}")
void updateUser(User user);
/**
* 刪除用戶
* @param id
*/
@Delete("delete from user where id=#{id}")
void deleteUser(Integer id);
/**
* 查詢用戶根據(jù)ID
* @param id
* @return
*/
@Select("select * from user where id=#{id}")
@ResultMap(value = {"userMap"})
User findById(Integer id);
/**
* 根據(jù)用戶名稱查詢用戶
* @param name
* @return
*/
// @Select("select * from user where username like #{name}")
@Select("select * from user where username like '%${value}%'")
List<User> findByUserName(String name);
/**
* 查詢用戶數(shù)量
* @return
*/
@Select("select count(*) from user")
int findTotalUser();
在findAll()方法中配置@Results的返回值的注解,在@Results注解中使用@Result配置根據(jù)用戶和賬戶的關(guān)系而添加的屬性,User中的屬性List<Account>一個用戶有多個賬戶的關(guān)系的映射配置:@Result(column = "id",property = "accounts",many = @Many(select = "com.example.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY)),使用@Many來向Mybatis表明其一對多的關(guān)系,@Many中的select屬性對應(yīng)的AccountDao中的findAccountByUid方法的全限定名,fetchType代表使用立即加載或者延遲加載,因為這里為一對多根據(jù)前面的講解,懶加載的使用方式介紹一對多關(guān)系一般使用延遲加載,所以這里配置為LAZY方式。在Account中存在多對一或者一對一關(guān)系,所以配置返回值屬性時使用:@Result(property = "user",column = "uid",one = @One(select = "com.example.dao.UserDao.findById",fetchType = FetchType.EAGER)),property代表領(lǐng)域類中聲明的屬性,column代表傳入后面select語句中的參數(shù),因為這里為一對一或者說為多對一,所以使用@One注解來描述其關(guān)系,EAGER表示使用立即加載的方式,select代表查詢本條數(shù)據(jù)時所用的方法的全限定名,fetchType代表使用立即加載還是延遲加載。
4.Demo中Mybatis的配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--<!–開啟全局的懶加載–>-->
<!--<setting name="lazyLoadingEnabled" value="true"/>-->
<!--<!–關(guān)閉立即加載,其實不用配置,默認(rèn)為false–>-->
<!--<setting name="aggressiveLazyLoading" value="false"/>-->
<!--開啟Mybatis的sql執(zhí)行相關(guān)信息打印-->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!--<setting name="cacheEnabled" value="true"/>-->
</settings>
<typeAliases>
<typeAlias type="com.example.domain.User" alias="user"/>
<package name="com.example.domain"/>
</typeAliases>
<environments default="test">
<environment id="test">
<!--配置事務(wù)-->
<transactionManager type="jdbc"></transactionManager>
<!--配置連接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test1"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.example.dao"/>
</mappers>
</configuration>
主要是記得開啟mybatis中sql執(zhí)行情況的打印,方便我們查看執(zhí)行情況。
5.測試
?。?)測試查詢用戶同時查詢出其賬戶的信息
測試代碼:
public class UserTest {
private InputStream in;
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
private UserDao userDao;
@Before
public void init()throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
sqlSession = sqlSessionFactory.openSession();
userDao = sqlSession.getMapper(UserDao.class);
}
@After
public void destory()throws Exception{
sqlSession.commit();
sqlSession.close();
in.close();
}
@Test
public void testFindAll(){
List<User> userList = userDao.findAll();
for (User user: userList){
System.out.println("每個用戶信息");
System.out.println(user);
System.out.println(user.getAccounts());
}
}
測試結(jié)果:

(2)查詢所有賬戶信息同時查詢出其所屬的用戶信息
測試代碼:
public class AccountTest {
private InputStream in;
private SqlSessionFactory sqlSessionFactory;
private SqlSession sqlSession;
private AccountDao accountDao;
@Before
public void init()throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
sqlSession = sqlSessionFactory.openSession();
accountDao = sqlSession.getMapper(AccountDao.class);
}
@After
public void destory()throws Exception{
sqlSession.commit();
sqlSession.close();
in.close();
}
@Test
public void testFindAll(){
List<Account> accountList = accountDao.findAll();
for (Account account: accountList){
System.out.println("查詢的每個賬戶");
System.out.println(account);
System.out.println(account.getUser());
}
}
}
測試結(jié)果:

總結(jié)
以上所述是小編給大家介紹的Mybatis基于注解實現(xiàn)多表查詢功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
淺談Spring中@Transactional事務(wù)回滾及示例(附源碼)
本篇文章主要介紹了淺談Spring中@Transactional事務(wù)回滾及示例(附源碼),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12
FastDFS分布式文件系統(tǒng)環(huán)境搭建及安裝過程解析
這篇文章主要介紹了FastDFS分布式文件系統(tǒng)環(huán)境搭建及安裝過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08
詳解多云架構(gòu)下的JAVA微服務(wù)技術(shù)解析
本文介紹了基于開源自建和適配云廠商開發(fā)框架兩種構(gòu)建多云架構(gòu)的思路,以及這些思路的優(yōu)缺點2021-05-05
SpringSecurity中的表單認(rèn)證詳細(xì)解析
這篇文章主要介紹了SpringSecurity中的表單認(rèn)證詳細(xì)解析,在上一篇文章中,我們初步引入了?Spring?Security,并使用其默認(rèn)生效的?HTTP?基本認(rèn)證保護(hù)?URL?資源,在本篇文章中我們使用表單認(rèn)證來保護(hù)?URL?資源,需要的朋友可以參考下2023-12-12

