Mybatis lazy loading implementation and usage scenarios

  First, let's think about a problem, hypothesis: in many, we have a user, he has 100 accounts.

  Question 1: When the user query, the associated account would want to check out?

  Question 2: query account when the associated user would want to check out?

  ANSWER: When a user queries, user account information at what time we should use, when to query.

     When the check account, your user account information should check out as account inquiries when together.

  After figuring out these two simple questions, we can immediately lead to lazy loading and load characteristics.

  Lazy loading : only initiate an inquiry in real time using data, not the data associated when not queries, also known as lazy loading demand query (lazy loading)

  Load Now : whether used or not, as long as a method is called immediately initiate an inquiry.

  Usage scenarios : the corresponding relationship table four, one-to-many general uses the delay loading, many to one, one uses the normally loaded immediately.

  Look Mybatis understand how to achieve a delay after delay loading loading characteristics of query method, in MyBatis configuration files were open to true global lazy loading by setting lazyLoadingEnabled property settings, and open the load immediately by aggressiveLazyLoading property. Look at the official website of the introduction, and then to implement lazy loading Mybatis by one instance, in the example we show the next-to-many relationships between tables, the query user information through the realization of a functional account information simultaneously query the user has to show what delay loading and delayed implementation of the results of load and load immediate differs.

lazyLoadingEnabled Delay global switch loaded. When turned on, all associations will be delayed loading. Specific association may be provided by  fetchType  to cover the switching state of the property. true | false false
aggressiveLazyLoading When turned on, any method invocation will load all the object's properties. Otherwise, each property will be loaded on demand (refer  lazyLoadTriggerMethods ). true | false false (in versions 3.4.1 and earlier defaults to true)

  

 

  And user account class 1. Class

public class User implements Serializable{
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    private List<Account> accountList;

    get和set方法省略.....      
}


public class Account implements Serializable{
    private Integer id;
    private Integer uid;
    private Double money;

    get和set方法省略.....      
}

Note that because we have to find out is to find the user's account while they have so we need to increase the collection of properties in the account of the user class for the result of the package returned.

  2. UserDao declared in the interface method findAll

/ ** 
     * Query all users 
     * 
     * @return 
     * / 
    List <the User> findAll ();

  3. findAll configuration mapping method in the UserDao.xml

<resultMap id="userAccountMap" type="com.example.domain.User">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="birthday" column="birthday"/>
        <result property="sex" column="sex"/>
        <result property="address" column="address"/>
        <collection property="accountList" ofType="com.example.domain.Account" column="id"
                    select="com.example.dao.AccountDao.findAllByUid"/>
    </resultMap>
    <select id="findAll" resultMap="userAccountMap">
        SELECT * FROM USER;
    </select>

  The main functions implemented positioned <collection property = "accountList" ofType = "com.example.domain.Account" column = "id" select = "com.example.dao.AccountDao.findAllByUid" />, the information for the account list set of maps through the collection, each element in the collection specified by the select how to query, findAllByUid namespace com.example.dao.AccountDao path method in the present embodiment a select attribute value AccountDao.xml file and specifies the mapping file by this way that uniquely identifies the specified search elements in the collection. Because here will need to find an account based on user ID, you can achieve findAllByUid methods need to configure it.

  Configuring a select attribute collection methods used findAllByUid

Add AccountDao interface 
 / ** 
     * The user ID account information query 
     * @return 
     * / 
    List < the Account > findAllByUid (Integer UID); 

AccountDao.xml configuration file 
< SELECT ID = "findAllByUid" the resultType = "com.example.domain .Account " > 
        the SELECT * the FROM Account the WHERE UID UID = # {}; 
    </ SELECT >

  5. Turn on the global load delay profile Mybatis

the Configuration>
     < Settings > 
        <-! Enable global lazy loaded -> 
        < Setting name = "lazyLoadingEnabled" value = "to true" />
         <-! Close load immediately, in fact, no configuration, the default is false -> 
        < Setting name = "aggressiveLazyLoading" value = "false" /> 
        <-! open Mybatis sql execution of print-related information -> 
        < Setting name = "logImpl" value = "STDOUT_LOGGING"  /> 
    </ Settings > 
    < typeAliases >
        <typeAlias type="com.example.domain.Account" alias="account"/>
        <typeAlias type="com.example.domain.User" alias="user"/>
        <package name="com.example.domain"/>
    </typeAliases>
    <environments default="test">
        <environment id="test">
            <!--配置事务-->
            <transactionManager type="jdbc"></transactionManager>
            <->Configure Connection Pool<! -
            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>
    </ ->Path configuration mapping file<-!>Environments
    
    <mappers>
        <mapper resource="com/example/dao/UserDao.xml"/>
        <mapper resource="com/example/dao/AccountDao.xml"/>
    </mappers>
</configuration>

  6. Test Methods

    private InputStream in;
    private SqlSession session;

    private UserDao userDao;
    private AccountDao accountDao;
    private SqlSessionFactory factory;
    @Before
    public void init()throws Exception{
        //获取配置文件
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //获取工厂
        factory = new SqlSessionFactoryBuilder().build(in);

        session = factory.openSession();

        userDao = session.getMapper(UserDao.class);
        accountDao = session.getMapper(AccountDao.class);
    }
    @After
    public void destory()throws Exception{
        session.commit();
        session.close();
        in.close();
    }
    @Test
    public void findAllTest(){
        List<User> userList = userDao.findAll();
//        for (User user: userList){
//            System.out.println("每个用户的信息");
//            System.out.println(user);
//            System.out.println(user.getAccountList());
//        }
    }

Test Description: When we annotated findAllTest () method for printing cycle, we will not need the user's account information, according to the characteristics of the delay in loading the program will query the user's information, but does not query account information. When I let go of the for loop we print, we use the information to users and accounts, the program will also print out the user and the corresponding account information.

  7. Test results

  (1) Notes for recycling, not using the data, at this time do not need to check account information, we can see the results in the console sql is because adding a logImpl configuration in Mybatis profile, with particular reference to the configuration of step 5 information

    (2) data for print query cycle, the use of data, this time because of the use of the data so check account information, we found that users and account inquiries are carried out execution

Guess you like

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