對應的四種數據庫表關系中存在四種關系:一對多,多對應,一對一,多對多。在前文中已經實現了xml配置方式實現表關系的查詢,本文記錄一下Mybatis怎么通過注解實現多表的查詢,算是一個知識的補充。
同樣的先介紹一下Demo的情況:存在兩個實體類用戶類和賬戶類,用戶類可能存在多個賬戶,即一對多的表關系。每個賬戶只能屬於一個用戶,即一對一或者多對一關系。我們最后實現兩個方法,第一個實現查詢所有用戶信息並同時查詢出每個用戶的賬戶信息,第二個實現查詢所有的賬戶信息並且同時查詢出其所屬的用戶信息。
1.項目結構
2.領域類
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的對象。
3.Dao層

1 public interface AccountDao { 2 /** 3 *查詢所有賬戶並同時查詢出所屬賬戶信息 4 */ 5 @Select("select * from account") 6 @Results(id = "accountMap",value = { 7 @Result(id = true,property = "id",column = "id"), 8 @Result(property = "uid",column = "uid"), 9 @Result(property = "money",column = "money"), 10 //配置用戶查詢的方式 column代表的傳入的字段,一對一查詢用one select 代表使用的方法的全限定名, fetchType表示查詢的方式為立即加載還是懶加載 11 @Result(property = "user",column = "uid",one = @One(select = "com.example.dao.UserDao.findById",fetchType = FetchType.EAGER)) 12 }) 13 List<Account> findAll(); 14 15 /** 16 * 根據用戶ID查詢所有賬戶 17 * @param id 18 * @return 19 */ 20 @Select("select * from account where uid = #{id}") 21 List<Account> findAccountByUid(Integer id); 22 } 23 24 25 26 public interface UserDao { 27 /** 28 * 查找所有用戶 29 * @return 30 */ 31 @Select("select * from User") 32 @Results(id = "userMap",value = {@Result(id = true,column = "id",property = "userId"), 33 @Result(column = "username",property = "userName"), 34 @Result(column = "birthday",property = "userBirthday"), 35 @Result(column = "sex",property = "userSex"), 36 @Result(column = "address",property = "userAddress"), 37 @Result(column = "id",property = "accounts",many = @Many(select = "com.example.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY)) 38 }) 39 List<User> findAll(); 40 41 /** 42 * 保存用戶 43 * @param user 44 */ 45 @Insert("insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})") 46 void saveUser(User user); 47 48 /** 49 * 更新用戶 50 * @param user 51 */ 52 @Update("update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}") 53 void updateUser(User user); 54 55 /** 56 * 刪除用戶 57 * @param id 58 */ 59 @Delete("delete from user where id=#{id}") 60 void deleteUser(Integer id); 61 62 /** 63 * 查詢用戶根據ID 64 * @param id 65 * @return 66 */ 67 @Select("select * from user where id=#{id}") 68 @ResultMap(value = {"userMap"}) 69 User findById(Integer id); 70 71 /** 72 * 根據用戶名稱查詢用戶 73 * @param name 74 * @return 75 */ 76 // @Select("select * from user where username like #{name}") 77 @Select("select * from user where username like '%${value}%'") 78 List<User> findByUserName(String name); 79 80 /** 81 * 查詢用戶數量 82 * @return 83 */ 84 @Select("select count(*) from user") 85 int findTotalUser();
在findAll()方法中配置@Results的返回值的注解,在@Results注解中使用@Result配置根據用戶和賬戶的關系而添加的屬性,User中的屬性List<Account>一個用戶有多個賬戶的關系的映射配置:@Result(column = "id",property = "accounts",many = @Many(select = "com.example.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY)),使用@Many來向Mybatis表明其一對多的關系,@Many中的select屬性對應的AccountDao中的findAccountByUid方法的全限定名,fetchType代表使用立即加載或者延遲加載,因為這里為一對多根據前面的講解,懶加載的使用方式介紹一對多關系一般使用延遲加載,所以這里配置為LAZY方式。在Account中存在多對一或者一對一關系,所以配置返回值屬性時使用:@Result(property = "user",column = "uid",one = @One(select = "com.example.dao.UserDao.findById",fetchType = FetchType.EAGER)),property代表領域類中聲明的屬性,column代表傳入后面select語句中的參數,因為這里為一對一或者說為多對一,所以使用@One注解來描述其關系,EAGER表示使用立即加載的方式,select代表查詢本條數據時所用的方法的全限定名,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"/>--> <!--<!–關閉立即加載,其實不用配置,默認為false–>--> <!--<setting name="aggressiveLazyLoading" value="false"/>--> <!--開啟Mybatis的sql執行相關信息打印--> <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"> <!--配置事務--> <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執行情況的打印,方便我們查看執行情況。
5.測試
(1)測試查詢用戶同時查詢出其賬戶的信息
測試代碼:
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()); } }
測試結果:
(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()); } } }
測試結果: