您好,登錄后才能下訂單哦!
本篇文章為大家展示了Mybatis中怎么利用注解實(shí)現(xiàn)多表查詢功能,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
1.項(xiàng)目結(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中因?yàn)橐粋€用戶有多個賬戶所以添加Account的列表,在Account中因?yàn)橐粋€賬戶只能屬于一個User,所以添加User的對象。
3.Dao層
public interface AccountDao { /** *查詢所有賬戶并同時(shí)查詢出所屬賬戶信息 */ @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代表使用立即加載或者延遲加載,因?yàn)檫@里為一對多根據(jù)前面的講解,懶加載的使用方式介紹一對多關(guān)系一般使用延遲加載,所以這里配置為LAZY方式。在Account中存在多對一或者一對一關(guān)系,所以配置返回值屬性時(shí)使用:@Result(property = "user",column = "uid",one = @One(select = "com.example.dao.UserDao.findById",fetchType = FetchType.EAGER)),
property代表領(lǐng)域類中聲明的屬性,column代表傳入后面select語句中的參數(shù),因?yàn)檫@里為一對一或者說為多對一,所以使用@One注解來描述其關(guān)系,EAGER表示使用立即加載的方式,select代表查詢本條數(shù)據(jù)時(shí)所用的方法的全限定名,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)閉立即加載,其實(shí)不用配置,默認(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.測試
?。?)測試查詢用戶同時(shí)查詢出其賬戶的信息
測試代碼:
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)查詢所有賬戶信息同時(shí)查詢出其所屬的用戶信息
測試代碼:
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()); } }}
上述內(nèi)容就是Mybatis中怎么利用注解實(shí)現(xiàn)多表查詢功能,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。