今天就跟大家聊聊有關(guān)怎么在Mybatis中利用注解實(shí)現(xiàn)一個(gè)多表查詢功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
從策劃到設(shè)計(jì)制作,每一步都追求做到細(xì)膩,制作可持續(xù)發(fā)展的企業(yè)網(wǎng)站。為客戶提供做網(wǎng)站、成都網(wǎng)站制作、網(wǎng)站策劃、網(wǎng)頁設(shè)計(jì)、國際域名空間、雅安服務(wù)器托管、網(wǎng)絡(luò)營銷、VI設(shè)計(jì)、 網(wǎng)站改版、漏洞修補(bǔ)等服務(wù)。為客戶提供更好的一站式互聯(lián)網(wǎng)解決方案,以客戶的口碑塑造優(yōu)易品牌,攜手廣大客戶,共同發(fā)展進(jìn)步。
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)橐粋€(gè)用戶有多個(gè)賬戶所以添加Account的列表,在Account中因?yàn)橐粋€(gè)賬戶只能屬于一個(gè)User,所以添加User的對(duì)象。
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代表的傳入的字段,一對(duì)一查詢用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>一個(gè)用戶有多個(gè)賬戶的關(guān)系的映射配置:@Result(column = "id",property = "accounts",many = @Many(select = "com.example.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY)),
使用@Many來向Mybatis表明其一對(duì)多的關(guān)系,@Many中的select屬性對(duì)應(yīng)的AccountDao中的findAccountByUid方法的全限定名,fetchType代表使用立即加載或者延遲加載,因?yàn)檫@里為一對(duì)多根據(jù)前面的講解,懶加載的使用方式介紹一對(duì)多關(guān)系一般使用延遲加載,所以這里配置為LAZY方式。在Account中存在多對(duì)一或者一對(duì)一關(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)檫@里為一對(duì)一或者說為多對(duì)一,所以使用@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.測(cè)試
(1)測(cè)試查詢用戶同時(shí)查詢出其賬戶的信息
測(cè)試代碼:
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("每個(gè)用戶信息"); System.out.println(user); System.out.println(user.getAccounts()); } }
測(cè)試結(jié)果:
(2)查詢所有賬戶信息同時(shí)查詢出其所屬的用戶信息
測(cè)試代碼:
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("查詢的每個(gè)賬戶"); System.out.println(account); System.out.println(account.getUser()); } } }
測(cè)試結(jié)果:
看完上述內(nèi)容,你們對(duì)怎么在Mybatis中利用注解實(shí)現(xiàn)一個(gè)多表查詢功能有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
網(wǎng)頁題目:怎么在Mybatis中利用注解實(shí)現(xiàn)一個(gè)多表查詢功能
地址分享:http://jinyejixie.com/article36/ggsspg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)、網(wǎng)站建設(shè)、服務(wù)器托管、電子商務(wù)、網(wǎng)站制作、云服務(wù)器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)