1. 程式人生 > >Mybatis基於註解實現多表查詢

Mybatis基於註解實現多表查詢

  對應的四種資料庫表關係中存在四種關係:一對多,多對應,一對一,多對多。在前文中已經實現了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();
View Code

  在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>
        <!--&lt;!&ndash;開啟全域性的懶載入&ndash;&gt;-->
        <!--<setting name="lazyLoadingEnabled" value="true"/>-->
        <!--&lt;!&ndash;關閉立即載入,其實不用配置,預設為false&ndash;&gt;-->
        <!--<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());
        }
    }
}

測試結果:

&n