MyBaits introduction and conclusion, senior Java development engineer of Netease

Posted by Jas on Wed, 15 Dec 2021 02:51:32 +0100

trim tag

Intercept string

Prefix = "": prefix. Add a prefix to the following sql statements as a whole

prefixOverrides = "": take out possible extra characters in front of the whole string

Suffix = "": add a suffix to the whole

suffixOverrides = "": take out the characters that may be used after the whole string

The following will automatically help us add a where prefix and remove the first and last and of the whole

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Com.MyBaits.KeyDao.LockDao">

<!--if label-->

    <select id="getLockByCondition" resultType="Com.MyBaits.KeyAndLock.Lock">

        SELECT l.id,l.lockName `name`,l.price FROM `lock` l

        <trim prefix="where" prefixOverrides="and" suffixOverrides="and">

       <if test="id!=null">

           and id > #{id}

       </if>

       <if test="name!=null  and name!=&quot;&quot;">

           and lockName like #{name}

       </if>

       <if test="price!=null">

           and price &lt; #{price} and

       </if>

   </trim>

    </select>

</mapper> 

foreach tag

LockDao interface class:

public interface LockDao {

    public List<Lock> getLockByCondition(@Param("list") List<Integer> listId);

} 

LockDao.xml:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Com.MyBaits.KeyDao.LockDao">

<!--if label-->

    <select id="getLockByCondition" resultType="Com.MyBaits.KeyAndLock.Lock">

        SELECT l.id,l.lockName `name`,l.price FROM `lock` l WHERE id IN

/*For the list set, the key is list by default. We can also specify the key value of the parameter ourselves*/

 <foreach collection="list" close=")" item="id_item" open="(" separator=",">

            #{id_item}

 </foreach>

    </select>

</mapper> 

main:

public class main {

    static  SqlSessionFactory sqlSessionFactory;

    static public void initSqlSessionFactory() throws IOException {

        String resource = "MyBaits-config.xml";

        InputStream inputStream = Resources.getResourceAsStream(resource);

        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    }

    public static void main(String[] args) throws IOException

    {

        initSqlSessionFactory();

        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        try{

            LockDao lock = sqlSession.getMapper(LockDao.class);

            List<Integer> idList=new LinkedList<Integer>();

            idList.add(1);

            idList.add(2);

            idList.add(3);

            idList.add(4);

            idList.add(5);

            List<Lock> lockList = lock.getLockByCondition(idList);

            for(Lock l:lockList)

            {

                System.out.println(1);

            }

        }finally

        {

            sqlSession.close();

        }

    }

} 

Choose tag - used as if... else or switch

LockDao.xml :

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper

        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Com.MyBaits.KeyDao.LockDao">

<!--if label-->

    <select id="getLockByCondition" resultType="Com.MyBaits.KeyAndLock.Lock">

        SELECT l.id,l.lockName `name`,l.price FROM `lock` l

        <where>

            <choose>

                <when test="id !=null">id=#{id}</when>

<otherwise>id=2</otherwise>

            </choose>

        </where>



    </select>

</mapper> 

LockDao interface:

public interface LockDao {

    public Lock getLockByCondition(@Param("id") Integer id);

} 

If an object is passed in, it can be recognized when using the property name

There is no getter for property named ID in class java Lang. integer, set the key name for the parameter

Field part update ---- "if combined with set

 <update id="UpdateLock">

update `lock`

        <set>

            <if test="id&lt;=5 and id >=1">

                <if test="name!=null">lockName=#{name},</if>

                <if test="price!=null">price=#{price},</if>

            </if>

        </set>

    <where>

        id=#{id}

    </where>

    </update> 

OGNL expression

Not only can properties be called directly, but also methods can be called

Collection pseudo attribute in OGNL expression

//The premise is that list is a collection

<if test="list.size>0"></if> 

It can not only judge the parameters, but also judge_ parameter and_ databasedId

bind tag

The bind element allows you to create a variable outside the OGNL expression and bind it to the current context. For example:

<select id="selectBlogsLike" resultType="Blog">

  <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />

  SELECT * FROM BLOG

  WHERE title LIKE #{pattern}

</select> 

The sql tag and the include tag complete the extraction of duplicate sql statements

To use dynamic SQL in the annotated mapper interface class, you can use the script element

cache

=================================================================

L1 cache

L1 cache invalidation

Functions to manually empty the buffer:

 sqlSession.clearCache(); 

L2 cache: namespace level cache. The cache will be refreshed automatically after a period of time

Only after the sqlSession is closed or committed will the data be moved from the first level cache to the second level cache

Step 1: enable L2 cache in configuration file

 <!--Turn on the global cache switch-->

        <setting name="cacheEnabled" value="true"/> 

Step 2: use cache to configure the cache in the mapping file that needs to use L2 cache

<!--Use L2 cache-->

    <cache></cache> 

Step 3: the POJO object needs to implement the serialization interface

Related attributes in L2 cache tag

Cached query order

Cache principle - each dao has its own L2 cache

Cache related settings

Integrate third-party caching - here ehcache - a caching framework within java processes

1. Import dependency

 <!--ehcache Dependence on third-party professional caching framework-->

       <!--ehcache Core package-->

      <dependency>

          <groupId>net.sf.ehcache</groupId>

          <artifactId>ehcache-core</artifactId>

          <version>2.6.8</version>

      </dependency>

          <!--ehcache Consolidation package for-->

      <dependency>

          <groupId>org.mybatis.caches</groupId>

          <artifactId>mybatis-ehcache</artifactId>

          <version>1.0.3</version>

      </dependency>

          <!--except log4j,You also need to import slf4j Log package for-->

      <dependency>

          <groupId>org.slf4j</groupId>

          <artifactId>slf4j-api</artifactId>

          <version>1.7.21</version>

      </dependency>



      <dependency>

          <groupId>org.slf4j</groupId>

          <artifactId>slf4j-log4j12</artifactId>

          <version>1.7.21</version>

          <scope>test</scope>

      </dependency> 

2.ehcache requires a configuration file called ehcache XML in the root directory of the classpath

 <?xml version="1.0" encoding="UTF-8"?>

    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

             xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"

             updateCheck="false">

    

        <!--Persistent disk path-->

        <diskStore path="java.io.tmpdir"/>

    

    

    

        <!--Default cache settings-->

        <defaultCache maxElementsInMemory="1000"

                       eternal="false"

                       timeToIdleSeconds="3600"

                       timeToLiveSeconds="0"

                       overflowToDisk="true"

                       maxElementsOnDisk="10000"

                       diskPersistent="false"



Topics: Java Hibernate Back-end Programmer