This is the 15th day of my participation in the August More Text Challenge

Author: Tom Brother wechat official account: Micro technology

1, the introduction of

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all of the JDBC code and the work of setting parameters and fetching result sets. MyBatis can configure and map primitive types, interfaces, and Java POJOs (Plain Old Java Objects) to records in the database via simple XML files or annotations.

Unlike other ORM frameworks, MyBatis does not associate Java objects with database tables, but Java methods with SQL statements. Allows users to take full advantage of the various functions of the database.

Compared to JDBC, MyBatis simplifies the code so that SQL statements can be executed in a single line of code. Mybatis supports declarative caching. When a SQL query is marked as cacheable, the first SQL query from the database will be stored in a cache, and the subsequent execution of the statement will read the results from the cache, rather than query the database again. Mybatis not only implements the cache based on the default HashMap, but also supports OSCache, Ehcache, Memcached and other extended caches.

2. Dependency integration

First add mybatis spring Boot Start component, introduce POM dependency

<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> The < version > 1.3.0 < / version > < / dependency >Copy the code

Package dependencies:

Pom dependencies can be viewed through the MAVEN plugin for IDEA. Spring Boot 2 uses HikariCP as the default database connection pool.

HiKariCP is a new JDBC connection pool with BoneCP enhancements and optimisations. HiKariCP is a new JDBC connection pool with BoneCP enhancements. But the code size is relatively small, only 130kb.

Which is better, HikariCP versus Druid?

Druid is alibaba’s open source database connection pool for monitoring! . The performance testing process is slightly lower than HikariCP, but provides powerful monitoring and extension capabilities. Support psCache.

For more information, please refer to github.com/brettwooldr…

The other database drivers need to be introduced manually, with specific POM dependencies

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

Copy the code

3. Code demonstration

Configuring a Data Source

Yaml datasource configuration prefix is spring.datasource. The hikari connection pool is configured using spring.datasource.

Spring: a datasource: driver - class - name: com. Mysql. Cj). The JDBC driver url: JDBC: mysql: / / 127.0.0.1:3306 / ds0? characterEncoding=utf-8 username: root password: 111111 # Hikari config type: com.zaxxer.hikari.HikariDataSource hikari: minimum-idle: 10 maximum-pool-size: 200 idle-timeout: 60000 pool-name: MarketingHikariCP max-lifetime: 1800000 connection-timeout: 2000 connection-test-query: select 1Copy the code

The earlier use of com.mysql.jdbc.driver for database drivers has been marked as obsolete. Now use com.mysql.cj.jdbc.driver.

Mybatis related configuration

Mybatis configuration is relatively few, mainly entity class, *Mapper interface, * mapper.xml, mybatis some framework extension configuration

The mappers folder in resources is now the mappers folder in the classpath, so you need to configure the following in application.yaml

mybatis:
  config-location: classpath:config/mybatis-config.xml

Copy the code

The contents of the corresponding user.xml file:

<mapper namespace="com.weiguanjishu.domain.mapper.UserMapper"> <resultMap id="userResultMap" type="com.weiguanjishu.domain.model.User"> <result column="id" property="id"/> <result column="user_name" property="userName"/> <result column="age" property="age"/> <result column="address" property="address"/> </resultMap> <! - insert the User - > < insert id = "addUser" parameterType = "com. Weiguanjishu. Domain. The model. The User" > < selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER"> SELECT LAST_INSERT_ID() </selectKey> insert into user (user_name,age,address) VALUES (#{userName}, #{age}, #{address}) </insert>Copy the code

If you want to print SQL statements for each request, simply declare the log level of the Mapper interface package as DEBUG

logging:
  level:
    com.weiguanjishu.domain.mapper: debug

Copy the code

4, SQL annotation method

In addition to placing SQL statements in XML files, MyBatis also supports annotation, directly writing SQL statements on the interface, such as: @INSERT, @update, @delete, @select, @Results, etc.

The @SELECT, @INSERT, @update, and @delete annotations correspond to the Select, Insert, Update, and Delete tags in XML respectively. The @Results annotation is similar to the ResultMap mapping file in XML.

@Mapper public interface PromotionShopMapper { String PROMOTION_SHOP_RESULT_MAP = "promotionShopResultMap"; @Insert({ "insert into promotion_shop (promotion_id,shop_id,shop_type,create_time,update_time,is_deleted) ", "values (#{promotionId},#{shopId},#{shopType},now(),now(),0)" }) @Options(useGeneratedKeys = true, keyProperty = "id") void insert(PromotionShopDO record); @Select("select * from promotion_shop where promotion_id = #{promotionId} and is_deleted = 0") @Results(id = PROMOTION_SHOP_RESULT_MAP, value = { @Result(column = "id", property = "id"), @Result(column = "promotion_id", property = "promotionId"), @Result(column = "shop_id", property = "shopId"), @Result(column = "shop_type", property = "shopType"), @Result(column = "create_time", property = "createTime"), @Result(column = "update_time", property = "updateTime"), @Result(column = "is_deleted", property = "isDeleted") }) List<PromotionShopDO> queryByPromotionId(@Param("promotionId") long promotionId); @Insert("<script>" + "insert into promotion_shop" + " (" + " promotion_id,shop_id,shop_type,create_time,update_time,is_deleted" + " )" + " values" + " <foreach collection='list' item='record' index='index' separator=','> " + " (#{record.promotionId},#{record.shopId},#{record.shopType},now(),now(),  0)" + " </foreach>" + " </script>") int insertBatch(@Param("list") List<PromotionShopDO> list); }Copy the code

Advantages: intuitive, high efficiency.

Disadvantages: The code needs to be recompiled when the SQL changes. Annotations are generally not recommended.

5, the project source address

Github.com/aalansehaiy…

Module: spring – the boot – bulking – mybatis

Author introduction: Tom brother, computer graduate student, the school recruited ali, P7 technical expert, has a patent, CSDN blog expert. Responsible for e-commerce transactions, community fresh, flow marketing, Internet finance and other businesses, many years of first-line team management experience