Mybatis basic knowledge

Execution process of Mybatis

    1. Load the MyBatis configuration file and get an input stream
    1. SqlSessionFactory is a singleton; SqlSessionFactoryBuilder().build() is a singleton; Equivalent to a database connection pool
    1. Through SqlSessionFactory. OpenSession (), obtain SqlSession
    1. Executive xxMapper SqlSession. XML
    1. sqlSession.close();
String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); List list = sqlSession.selectList("com.foo.bean.BlogMapper.queryAllBlogInfo"); // commit transaction sqlSession.com MIT (); // Close connection sqlsession.close ();Copy the code

Configuration Several important properties in the configuration file

typeAliases

Alias of the bean; There are two ways: 1. </ SELECT > <select ID ="selById2" resultType="user" > select * from people where id= #{id} </select In configuration. XML <typeAliases> <typeAlias type="com.xx.User" alias=" User" /> </typeAliases> or <typeAliases> <! <package name="com.xx"/> </typeAliases> 2. @alias ("user") public class user {... }Copy the code

properties

There are three ways to use it:

1: Add the property property to the Properties property, The name used to set some properties, value <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> 2: introduce the external configuration class <properties resource="db.properties" /> 3: String resource = "mybatis-config.xml"; String resource = "mybatis-config.xml"; InputStream is = Resources.getResourceAsStream("db.properties"); Properties properties = new Properties(); properties.load(is); String userName = properties.getProperty("db.username"); String pwd = properties.getProperty("db.pwd"); properties.setProperty("db.username", CyperTool.decodeByBase64(userName));Copy the code

settings

<settings>
		<setting name="cacheEnabled" value="true" />
		<setting name="useGeneratedKeys" value="true" />
		<setting name="defaultExecutorType" value="REUSE" />
		<setting name="logImpl" value="STDOUT_LOGGING" /> // 
</settings>
Copy the code
  • CacheEnabled // Enables or disables caching globally, true/false
  • LazyLoadingEnabled // Global lazy loading switch
  • Logimpl // Specify the specific implementation of mybatis logging. If not specified, it will be automatically found

Xxmapper.xml important attributes

ResultMap Indicates the mapping of result sets

Set up database field and bean property mappings

<resultMap id="BaseResultMap" type="com.xx.User">
    <id column="ID" jdbcType="BIGINT" property="id" />
    <result column="SKU_NAME" jdbcType="VARCHAR" property="skuName" />
    <result column="CATEGORY_ID" jdbcType="BIGINT" property="categoryId" />
</resultMap> 

<select id="getUserList" resultMap="BaseResultMap" parameterType="User">

Copy the code

Mybatis paging

1. Limit 2. Use RowBoundsCopy the code

annotations

Public interface UserMapper {@select (" Select * from user") List< user > findAll(); }Copy the code

Multiple arguments @param

Can only be used on element parameters

Public User selectUser(@param(" userName ")String name,@param(" userArea ")String area); <select id=" selectUser" resultMap="BaseResultMap"> select * from user_user_t where user_name = #{userName, jdbcType=VARCHAR} and user_area=#{userArea,jdbcType=VARCHAR} </select>Copy the code

${} and #{}

#{} is precompiled to prevent SQL injection

Association, collection,

<resultMap type="Student" id="studentResultMap"> <id column="id" property="id" /> <result column="name" property="name" /> <result column="gender" property="gender" /> <result column="major" property="major" /> <result column="grade" Property = "grade" / > / / collection - a one-to-many < collection property = "emps ofType" = "com. Mybatis. Bean. The Employee" > < id column = "eid" property="id"/> <result column="last_name" property="lastName"/> <result column="email" property="email"/> <result Column ="gender" property="gender"/> </ Collection > // object - many-to-one <association Property =" Supervisor "javaType="Teacher"> < ID  property="id" column="t_id"/> <result property="name" column="t_name"/> <result property="gender" column="t_gender"/> <result property="researchArea" column="research_area"/> </association> </resultMap> # ofType: Specifies the type of the attribute in the entity classCopy the code

Dynamic SQL

Generate different SQL according to different conditions, Mybatis dynamic SQL based on OGNL expression

if <select id="dynamicIfTest" parameterType="Blog" resultType="Blog"> select * from t_blog where 1 = 1 <if test="title ! = null"> and title = #{title} </if> <if test="content ! = null"> and content = #{content} </if> <if test="owner ! = null"> and owner = #{owner} </if> </select>Copy the code
choose <select id="dynamicChooseTest" parameterType="Blog" resultType="Blog"> select * from t_blog where 1 = 1 <choose> <when test="title ! = null"> and title = #{title} </when> <when test="content ! = null"> and content = #{content} </when> <otherwise> and owner = "owner1" </otherwise> </choose> </select>Copy the code
trim <select id="dynamicTrimTest" parameterType="Blog" resultType="Blog"> select * from t_blog <trim prefix="where" prefixOverrides="and |or"> <if test="title ! = null"> title = #{title} </if> <if test="content ! = null"> and content = #{content} </if> <if test="owner ! = null"> or owner = #{owner} </if> </trim> </select>Copy the code
where <select id="dynamicWhereTest" parameterType="Blog" resultType="Blog"> select * from t_blog <where> <if test="title ! = null"> title = #{title} </if> <if test="content ! = null"> and content = #{content} </if> <if test="owner ! = null"> and owner = #{owner} </if> </where> </select>Copy the code
set <update id="dynamicSetTest" parameterType="Blog"> update t_blog <set> <if test="title ! = null"> title = #{title}, </if> <if test="content ! = null"> content = #{content}, </if> <if test="owner ! = null"> owner = #{owner} </if> </set> where id = #{id} </update>Copy the code
<select id="dynamicForeachTest" resultType="Blog" collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>Copy the code

Dynamic SQL include

Reference SQL fragment

<include refid = "" />
Copy the code

MyBatis cache

Frequently queried data is stored in memory as temporary data in order to reduce interaction with the database two levels of caching. Mybatis provides the Cache interface, which can be used to customize the Cache level. Mybatis provides the Cache interface, which can be used to customize the Cache level

Level 1 cache

Also called local cache, and the database during the same query (SqlSession open to close period) cache to the local cache, the next query the same data, directly obtain

Cache invalidation

  • Query for different things
  • Increases the deletion
  • Disable clearCache, sqlsession.clearcache ()

The second level cache

<! -- Enable level 2 cache --> < Settings > <setting name="cacheEnabled" value="true"/> </ Settings > Next enable cache <cache in usermapper. XML file eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>Copy the code

Caching mechanism principle of Mybatis

The first query first look at the level 2 cache, then look at the level 1 cache, did not go to the database, into the level 1 cache;

Use custom caches

TODO…..

Common version

3.x

Spring integration Mybatis

Steps:

    1. Import related JAR packages
      • junit
    • mybatis
    • The mysql database
    • Spring related
    • Aop weave
    • mybatis-spring
    1. Writing configuration files

xxMapper.xml

Namespace - Namespace. Bind a Mapper interface with the same name. 2 <select id ="xx" resultType =" com.xx..." > - resultType return value 4. Paramete type - parameter type 5. #{id} - placeholder for parameter 6.Copy the code

The interview questions

How are SqlSession and Mapper executed?

Uniquely located through the namespace of mapeer. XMLCopy the code

What is the default connection for Mybatis?

JDBC, the default connection pool modeCopy the code