Mybatis multi-table query based on the realization comment

  Corresponding to the four database table relationships exist in four relationships: many, more than the corresponding, one to one, many to many. In the foregoing has been achieved xml configuration for query table relationships, the paper record about how Mybatis achieve multi-table queries through annotations, regarded as a supplement knowledge.

  The same first introduce Demo situation: there are two entity classes user classes and account type, user class may be multiple accounts, that many table relationships. Each account can only belong to one user, or many-to-one relationship that is. We finally implement two methods, the first implementation of query all user information and also check out each user's account information, implementation of the second query all the account information and at the same time check out the user information to which they belong.

  1. Project Structure

 

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  2. The domain classes

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;
    privateList <the Account> Accounts; 
    omitted get and set methods .............................         
}

  In the User because a user has multiple accounts so add a list Account because an account can only belong to one User, so add the User object in the Account. 

  3.Dao layer

. 1  public  interface AccountDao {
 2      / ** 
. 3       * Search account while the account information relevant to the query
 . 4       * / 
. 5      @Select ( "SELECT * from Account" )
 . 6      @Results (ID = "accountMap", value = {
 . 7              @ the Result (= ID to true , = Property "ID", column = "ID" ),
 . 8              @Result (Property = "UID", column = "UID" ),
 . 9              @Result (Property = "Money", column = "Money " ),
10              // incoming field configuration of the user's query column represents the way, the fully qualified name of one query with one select representatives method used, fetchType representation of the query is immediately loaded or lazy loading 
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      * Number of user queries
 82       * @return 
83       * / 
84      @Select ( "SELECT COUNT (*) from User" )
 85      int findTotalUser ();
View Code

  Disposed in the findAll () method returns the value @Results annotations, using the configuration properties @Result relationship between the user account and added in @Results annotations, in the User Attribute List <Account> a user has multiple accounts mapping configuration relationship: @Result (column = "id", property = "accounts", many = @Many (select = "com.example.dao.AccountDao.findAccountByUid", fetchType = FetchType.LAZY)), using @Many to indicate its relationship to many Mybatis, the fully qualified name of the method findAccountByUid select attribute corresponding AccountDao @ many of the representative fetchType immediately load or delay loading, because there is a one to many of the foregoing explanation, lazy loading use introduction-to-many relationship between the general use of lazy loading, so here is configured LAZY way. Or many-to-one relationship exists in the Account, the use of configuration attributes Return Value: @Result (property = "user", column = "uid", one = @One (select = "com.example.dao. UserDao.findById ", fetchType = FetchType.EAGER)), property on behalf of property class field declared, on behalf of column parameters passed back in the select statement, because there is one or many to one, so use @One annotations to describe their relationship, EAGER representation immediately loaded, select representatives fully qualified name of the query data used in this article methods, fetchType representatives use to load immediately or delayed loading.

 

  4.Demo in Mybatis configuration

<? Xml Version = "1.0" encoding = "UTF-8" ?> 
<! DOCTYPE the Configuration 
        the PUBLIC "- // mybatis.org//DTD Config 3.0 // EN" 
        "http://mybatis.org/dtd/mybatis config.dtd--3 " > 
< Configuration > 
    < Settings > 
        <-! & lt; & ndash; lazy loading opening globally ndash &; & gt;! -> 
        ! <- <Setting name =" lazyLoadingEnabled "value =" to true "/> -> 
        ! <- & lt; & ndash; off load immediately, in fact, not configured, the default is to false & ndash; & gt;! -> 
        ! <- <Setting name =" aggressiveLazyLoading "value =" to false "/>-> 
        <! - open Mybatis sql execution of print-related information -> 
        < 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<->Configuration Services<! -
            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>

 

  I remember mainly the implementation of open mybatis print in sql, help us to see the implementation.

  5. Test

  (1) test queries users simultaneously check out their account information

   Test code:

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());
        }
    }

  Test Results:

(2) All account information query query user information at the same time it belongs

  Test code:

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());
        }
    }
}

Test Results:

 

Guess you like

Origin www.cnblogs.com/hopeofthevillage/p/11444485.html