MyBatis annotation usage, ORM layer optimization (lazy loading and caching)

Mybatis annotation

  • find
      @Select( "SELECT * FROM tt_user WHERE username Like #{id};")
      User findUserByName(String name);

      <!--以map为输入参数查找-->
      @Select("select * from tt_user where username= #{name} and  password=#{pass}")
      User findUserByUsernameAndPassword(HashMap map);
  • insert
      @Insert("insert into tt_user values (#{id},#{username},#{password},#{email},#{age})")
      int AddUser(User user) throws IOException;
  • Change
      @Update("update tt_user set username = #{username} where id = #{id}")
      void updateUserById(User user);
  • delete
      @Delete("delete from tt_user where id =#{id}")
      void deleteUserById(String id);
  • Dynamic SQL Statements
      @SelectProvider(type = UserDaoSqlProvider.class,method = "findUserByName")
      List<User> findUserByName(String username) throws IOException;
    public String findUserByName(String username){
        //return  "select * from tt_user where username like '" +username+"'";
        String sql = new SQL() {{
            SELECT("*");
            FROM("tt_user");
            if (username!=null&&!username.isEmpty()){
                WHERE("username like "+username );
            }
        }}.toString();
        System.out.println("sql="+sql);
        return sql;
}

Mybatis provides an anonymous inner class
write picture description here

Another way of writing:

    public String getxxx(){

       return new SQL().UPDATE("PERSON")
                 .SET("FULL_NAME = #{fullName}", "DATE_OF_BIRTH = #{dateOfBirth}")
                 .WHERE("ID = #{id}")
                 .toString();
    }
}

Mybatis optimization of ORM layer

cache

After checking it once, the results are saved locally, so you don't need to access the database the next time you check the same content.

lazy loading

Lazyloading: Load the main information first, and then load the associated data when
needed. The association and Collection tags in the ResultMap in Mybatis have the function of lazy loading

  • No lazy loading by default
  • How to enable lazy loading?
    Configured under the configuration tab in the main configuration file
    <!--全局懒加载-->
    <settings>
        <!--开关-->
        <setting name="lazyLoadingEnabled" value="true"/>
    </settings>
  • Local lazy loading configuration Add the fetchType field from the association or collection
    in the configuration file (fetch translation is take, take)
    <resultMap id="studentAndCourses" type="com.bamzhy.bean.Student">
        <id column="id" property="id"></id>
        <collection property="courses"
                    javaType="list"
                    select="com.bamzhy.dao.UserDao.findcourseBySid"
                    column="id"
                    fetchType="eager">
            <id column="cid" property="cid"></id>
        </collection>
    </resultMap>
  • When global lazy loading and local lazy loading appear at the same time, local lazy loading takes precedence;

MyBatis caching mechanism

write picture description here

L1 cache

  • The first-level cache refers to the sqlsession. There is a data area in the sqlsession, which is a map structure. This area is the first-level cache area.
    When querying the same object (using the same session), the second query does not call the sql statement, but fetches data from the sqlsession.
  • Enable L1 cache: enabled by default
  • Verify that the first level cache exists

write picture description here

I checked twice, but only executed the sql statement once
write picture description here

Now close the sqlSession after the first query, and then re-create a new session,
write picture description here

execute query
write picture description here

Sure enough, the sql statement was executed twice, which can prove that the first level cache does exist

L2 cache

The second-level cache refers to the mapper under the same namespace. There is also a map structure in the second-level cache, and this area is the second-level cache area.

  • Turn on the second-level cache Inside
    the main configuration file:
    write picture description here
    from the configuration file:
    write picture description here

  • Note that the cache object needs to implement the serialization interface, otherwise Error serializing object will be reported

  • Test the second level cache

write picture description here

Although I closed the sqlsession, the sql is still not executed twice.

write picture description here

Indicates that the second level cache does exist

  • If the L1 cache is not turned off, the L2 cache will not take effect.

For example, if I create a sqlsession, do not close it, and then create another sqlsession, then the second-level cache sees that the first sqlsession is not closed (the first-level cache takes effect), and the second-level cache will not take effect. In fact, the two sessions are not the same session, and the second-level cache does not take effect, so the SQL statement needs to be executed twice.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324422523&siteId=291194637