Spring Boot2: Integrating Mybatis infrastructure with Spring Boot2

Warehouse Address: spring-boot-learning
Welcome to star and fork, give some encouragement to the author

Preface

Mybatis was difficult to use initially, requiring various configuration files, entity classes, Dao layer mapping associations, and a large number of other configurations. mybatis-spring-boot-starter is Spring Boot+ Mybatis, which can be completely annotated without configuration files, or can be easily configured.

mybatis-spring-boot-starter

Official note: MyBatis Spring-Boot-Starter will help you use MyBatis with Spring Boot
In fact, Mybatis saw Spring Boot so hot and developed a set of solutions to make it lively, but it did solve many problems, and it did work smoothly. mybatis-spring-boot-starter has two main solutions, one is to use annotations to solve all problems, the other is to simplify the old tradition.

Of course, any schema needs to first introduce mybatis-spring-boot-starter's Pom file, and the latest version is 2.0.1.

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.1</version>
</dependency>

I usually use the XML minimalist schema, probably because of the hibernate usage used before.

Minimalist xml version

Minimalist xml version keeps the old tradition of mapping file. The interface layer only needs to define empty methods. The system will automatically find the corresponding Sql in the mapping file according to the method name.

1 Add related Maven files

<dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

The complete Pom package is not posted here, you can see the source code directly.

2. application.yml related configuration

It is recommended to use application.yml for configuration. In fact, using application.yml or application.properties is the same effect. application.yml is eventually converted to application.properties for effective, but the application.yml visual effect looks more clear. The new project defaults to application.properties and changes directly to application.yml. In addition, a new application-test.yml user uses different configuration files in different environments.

application.ymlTo configure:

#Specify the configuration file as test
spring:
  profiles:
    active: test

#Configure Mybatis
mybatis:
  type-aliases-package: com.niaobulashi.entity
  mapper-locations: classpath:mapper/*.xml
  configuration:
    # Turn on hump naming conversions, such as Table (create_time) - > Entity (create time). Without our concern about how to match fields, mybatis automatically recognizes `uppercase letters and underscores'.`
    map-underscore-to-camel-case: true

#Print SQL logs
logging:
  level:
    com.niaobulashi.dao: DEBUG

application-test.yml configuration:

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

Spring Boot will automatically load spring.datasource. * configuration, data source will automatically inject into sqlSession Factory, sqlSession Factory will automatically inject into Mapper, by the way, you don't have to worry about everything, just pick it up and use it.

Add a scan for mapper package @MapperScan to the startup class

@SpringBootApplication
@MapperScan("com.niaobulashi.dao")
public class MybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }

}

Or add a comment @Mapper directly to the Mapper class, recommend using the above one, otherwise it would be troublesome to add a comment to each mapper.

3. Examples of Adding User

@Data
public class SysUserEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    //User ID
    private Long userId;

    //User name
    private String username;

    //Password
    private String password;

    //salt
    private String salt;

    //mailbox
    private String email;

    //Cell-phone number
    private String mobile;

    //State 0: Disable 1: Normal
    private Integer status;
    
    //Creation time
    private Date createTime;
}

4. Adding User Mapping Files

<mapper namespace="com.niaobulashi.dao.SysUserDao">

    <!--Query all menus of users ID-->
    <select id="queryUserInfo" resultType="com.niaobulashi.entity.SysUserEntity">
        SELECT
            ur.*
        FROM
            sys_user ur
        WHERE
            1 = 1
          AND ur.user_id = #{userId}
    </select>

</mapper>

In fact, it's just moving Mapper's Sql from the previous version to xml here.

5. Writing Mapper Layer Code

public interface SysUserDao {
    /**
     * Query user information according to userId
     * @param userId  User ID
     */
    List<SysUserEntity> queryUserInfo(Long userId);
}

6. Writing Service Layer Code

SysUserService interface class:

public interface SysUserService {
    /**
     * Query all menu ID s of users
     */
    List<SysUserEntity> queryUserInfo(Long userId);
}

SysUserService Impl implementation class:

@Service("sysUserService")
public class SysUserServiceImpl  implements SysUserService {
    @Resource
    private SysUserDao sysUserDao;
    /**
     * Query all menu ID s of users
     * @param userId
     * @return
     */
    @Override
    public List<SysUserEntity> queryUserInfo(Long userId) {
        return sysUserDao.queryUserInfo(userId);
    }
}

7. Testing

The basic interface development can be accomplished by the above five steps, eliminating the development of the Controller layer.

@RunWith(SpringRunner.class)
@SpringBootTest
public class MabatisTest {
    private final static Logger logger = LoggerFactory.getLogger(MabatisTest.class);

    @Autowired
    private SysUserService sysUserService;

    @Test
    public void queryUserInfo() throws Exception {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setUserId(1L);
        List<SysUserEntity> list = sysUserService.queryUserInfo(userEntity.getUserId());
        logger.info("list:" + list);
    }

}

Final project directory structure

summary

SpringBoot and Mysteries are perfect for CP

Sample code - github

Keywords: Java Spring Mybatis xml MySQL

Added by mapleleaf on Sat, 20 Jul 2019 16:21:01 +0300