Spring Boot2 series of tutorials (21) Integration MyBatis

The previous two articles and readers chatted Spring Boot the most simple data persistence solution JdbcTemplate, JdbcTemplate is simple, but not much use, because it is not easy to MyBatis, MyBatis step in the integration of Spring + SpringMVC are still a little complicated, to configure multiple Bean, Spring Boot in this regard has been further simplified, so basically MyBatis can do out of the box, we take a look at how MyBatis to be used in the Spring Boot.

Project Creation

First create a basic Spring Boot project, add a Web-dependent, MyBatis rely and depend on the MySQL driver, as follows:

Once created, add Druid dependence, and locking MySQL driver version, complete dependence as follows:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.28</version>
    <scope>runtime</scope>
</dependency>

Thus, even if the project is to create success. Small partners note, MyBatis and Druid dependent naming and naming other libraries are not the same, belongs xxx-spring-boot-stater mode, which means that the starter is provided by a third party.

Basic Usage

MyBatis use and JdbcTemplate basically the same, the first and basic configuration information in the database in application.properties:

spring.datasource.url=jdbc:mysql:///test01?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

After configuration, MyBatis Mapper can be used to create, for example, I created a direct UserMapper2 here, as follows:

public interface UserMapper2 {
    @Select("select * from user")
    List<User> getAllUsers();

    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "username", column = "u"),
            @Result(property = "address", column = "a")
    })
    @Select("select username as u,address as a,id as id from user where id=#{id}")
    User getUserById(Long id);

    @Select("select * from user where username like concat('%',#{name},'%')")
    List<User> getUsersByName(String name);

    @Insert({"insert into user(username,address) values(#{username},#{address})"})
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id", before = false, resultType = Integer.class)
    Integer addUser(User user);

    @Update("update user set username=#{username},address=#{address} where id=#{id}")
    Integer updateUserById(User user);

    @Delete("delete from user where id=#{id}")
    Integer deleteUserById(Integer id);
}

Here is the full notes to write SQL by the way, do not write XML file.

@ Select, @ Insert, @ Update and @Delete four notes corresponding to the XML select, insert, update and delete tags, @ Results annotation similar ResultMap mapping file (getUserById method of XML query results to the field of major alias is small partners to demonstrate under @Resultsannotation usage).

Further @SelectKey annotations may be implemented using the primary key function backfill, i.e., when data insertion is successful, the success of the insertion data will be assigned to the user object id id attribute.

After UserMapper2 created, configure the mapper scan, there are two ways, one is added directly in UserMapper2 top @Mappernotes, this approach has a downside it is that all Mapper must manually add, if the fall will be a error, as well as a permanent solution is to add Mapper scan on startup class directly, as follows:

@SpringBootApplication
@MapperScan(basePackages = "org.javaboy.mybatis.mapper")
public class MybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}

Well, these jobs can be done to test the use of the Mapper.

mapper mapping

Of course, developers can write SQL in XML, such as creating a UserMapper, as follows:

public interface UserMapper {
    List<User> getAllUser();

    Integer addUser(User user);

    Integer updateUserById(User user);

    Integer deleteUserById(Integer id);
}

Then create UserMapper.xml file, as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-21-mapper.dtd">
<mapper namespace="org.javaboy.mybatis.mapper.UserMapper">
    <select id="getAllUser" resultType="org.javaboy.mybatis.model.User">
        select * from t_user;
    </select>
    <insert id="addUser" parameterType="org.javaboy.mybatis.model.User">
        insert into user (username,address) values (#{username},#{address});
    </insert>
    <update id="updateUserById" parameterType="org.javaboy.mybatis.model.User">
        update user set username=#{username},address=#{address} where id=#{id}
    </update>
    <delete id="deleteUserById">
        delete from user where id=#{id}
    </delete>
</mapper>

The interface method corresponding write SQL directly in the XML file.

So where in the end this UserMapper.xml put it? There are two positions can be placed, a first package is placed directly below UserMapper located:

UserMapper.xml placed here are automatically scanned, but there is another problem caused by Maven is xml resources under the java directory when the project package will be ignored, so if UserMapper.xml placed under the package, need to add the following configuration in the pom.xml file, avoid packaged XML files in the directory are automatically ignored java:

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
</build>

Of course, UserMapper.xml can also be placed directly under the resources directory, so do not worry about being overlooked when packing, but on the resources directory, you must create the same directory directory Mapper interface packet level, so as to ensure that packages and XML Mapper interfaces and in together, otherwise the XML file will not be automatically scanned, this time on the need to add additional configuration. For example, I created mapper directory in the resources directory to put the mapper file, as follows:

At this point in application.properties tell mybatis go where scanning mapper:

mybatis.mapper-locations=classpath:mapper/*.xml

After such a configuration, mapper can be used as normal. Note that this method does not require filtering profile pom.xml file.

Principle Analysis

In SSM integration, developers need to provide their own two Bean, a SqlSessionFactoryBean, there is a MapperScannerConfigurer, in Spring Boot, these two things though developers do not have to provide their own, but does not mean that the two Bean needed, in org.mybatis.spring.boot.autoconfigure.MybatisAutoConfigurationclass, we can see the Spring Boot provides both Bean, part of the source code as follows:

@org.springframework.context.annotation.Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration implements InitializingBean {

  @Bean
  @ConditionalOnMissingBean
  public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
    factory.setDataSource(dataSource);
    return factory.getObject();
  }
  @Bean
  @ConditionalOnMissingBean
  public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    ExecutorType executorType = this.properties.getExecutorType();
    if (executorType != null) {
      return new SqlSessionTemplate(sqlSessionFactory, executorType);
    } else {
      return new SqlSessionTemplate(sqlSessionFactory);
    }
  }
  @org.springframework.context.annotation.Configuration
  @Import({ AutoConfiguredMapperScannerRegistrar.class })
  @ConditionalOnMissingBean(MapperFactoryBean.class)
  public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {

    @Override
    public void afterPropertiesSet() {
      logger.debug("No {} found.", MapperFactoryBean.class.getName());
    }
  }
}

As it can be seen from the annotation on the class, when present SqlSessionFactory, SqlSessionFactoryBean current DataSource class path and, where the configuration will be effective, and a SqlSessionFactory SqlTemplate are provided. Why look at this code? Next article, Song Ge, and when everyone share in MyBatis configuration Spring Boot multiple data sources, there will be an important reference.

Well, this article on the first point, this paper related cases, you can download on GitHub: https://github.com/lenve/javaboy-code-samples

Public concern number [south] a little rain, focused on Spring Boot + Micro service and front and rear ends of separation full stack technology, video tutorials on a regular basis to share concerns reply after Java, Java dry Song Ge receive carefully prepared for you!

Guess you like

Origin www.cnblogs.com/lenve/p/11833025.html