Spring Boot (IV): How elegant use Mybatis

I. Introduction

Nature Orm framework is coded to simplify programming operation of the database, to the present, we only have basically declared a sql hibernate're welcome, one is flexible debugging mybatis dynamic sql, both of which have their own characteristics, enterprise-class system hair can be used flexibly according to demand. Found an interesting phenomenon: the most traditional companies like hibernate, the Internet industry generally use mybatis.

characterized sql hibernate all are used to generate java code, do not jump the program to write sql, an integrity of this program, the development is the top spring data jpa this mode, can be generated substantially corresponding to the name of the method according to sql .

Early mybatis use too much trouble, requires a variety of configuration files, the entity class, Dao layer mapping relationship, there are a lot of other configuration files.

Of course mybatis have found that drawbacks, early in the development of the generator can be automatically generated entity classes according to the table structure, configuration files, and dao level code, can reduce part of the developer amount; later also a lot of optimization may be used annotation, automatic management dao layer and configuration files, etc., to develop what is now talking about the top of this springboot + mybatis can not fully comment configuration file, you can simply configure easily get started.

springboot is Niubi ah, hell associated springboot can simplify.

二、mybatis-spring-boot-starter

mybatis-spring-boot-starter consists of two solutions, one is to use annotations to solve all problems, old traditional simplified one.

Of course, any mode need to introduce mybatis-spring-boot-starter of pom file, the latest version is now

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

Third, no configuration version comment

1, add maven file

<dependencies>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jdbc</artifactId>
   </dependency>

   <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.1.1</version>
   </dependency>

   <dependency>
      <groupId>com.oracle.ojdbc</groupId>
      <artifactId>ojdbc8</artifactId>
      <scope>runtime</scope>
   </dependency>

   <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
   <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.21</version>
   </dependency>

   <!-- https://mvnrepository.com/artifact/log4j/log4j -->
   <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
   </dependency>
</dependencies>

2, application.yml add configuration

spring:
  datasource:
    username: mine
    password: mine
    url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
    driver-class-name: oracle.jdbc.driver.OracleDriver
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

Spring Boot automatically loads spring.datasource. * Configuration, the data source is automatically injected into the sqlSessionFactory in sqlSessionFactory automatically injected into the Mapper, yes, everything you do not have control, directly take up the use of the line.

Add a packet mapper class start scanning @MapperScan

@MapperScan(value="com.demo.mapper")
@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

Or add annotations directly in the Mapper class above @Mapper , the kind recommended above, or to add a comment to each mapper also very troublesome

3、controller

@RestController
public class DeptController {
    @Autowired
    DepartmentMapper departmentMapper;

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id){
        return departmentMapper.getDeptById(id);
    }

    @GetMapping("/dept")
    public int insertDeptById(@PathVariable("id") Integer id,@PathVariable("departmentName") String departmentName){
        int ret = departmentMapper.insertDept(id,departmentName);
        return ret;
    }
}

4, the development mapper

package com.demo.mapper;

import com.demo.bean.Department;
import org.apache.ibatis.annotations.*;

public interface DepartmentMapper {
    @Select("select * from SSH_DEPARTMENT where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from SSH_DEPARTMENT where id=#{id}")
    public int deleteDeptById(Integer id);
    
    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into SSH_DEPARTMENT(department_name) values(#{departmentName})")
    public int insertDept(Department department);
    
    @Update("update SSH_DEPARTMENT set departmentName=#{DEPARTMENT_NAME} where id=#{id}")
    public int updateDept(Department department);
}
  • @Select  is annotated query class, all queries are using this
  • @Result  modified result set returned, related entity class properties and database fields correspond, if the entity class attributes and attribute database name remains the same, there is no need to modify this property.
  • @Insert  into the database use, directly into a value corresponding entity class attributes to automatically resolves
  • @Update  responsible for modifying or directly incoming object
  • @delete  responsible for deleting

4, run

The above three steps basically completed Mapper layer related to the development, use of time as a regular class will be able to inject into the

(1) inquiry

(2) Insert

  • Before inserting database state

  • The browser calls the controller performs an insert

  • After inserting the results of the query

Fourth, the minimalist version of XML

Xml mapping files kept minimalist version of the old tradition, the interface layer only need to define an empty method, the system will automatically find the corresponding method in the mapping file based on the name of Sql

1, the configuration

pom file and the previous version, just add the following configuration application.yml

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

mybatis-config.xml configuration

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

2、employeeMapper.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.atguigu.springboot.mapper.EmployeeMapper">
   <!--    public Employee getEmpById(Integer id);

    public void insertEmp(Employee employee);-->
    <select id="getEmpById" resultType="com.atguigu.springboot.bean.Employee">
        SELECT * FROM employee WHERE id=#{id}
    </select>

    <insert id="insertEmp">
        INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

3, development mapper

package com.demo.mapper;

import com.demo.bean.Employee;
import org.mybatis.spring.annotation.MapperScan;

@MapperScan
public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
    public void insertEmp(Employee employee);
}

Previous comparison, there only needs to define the interface methods.

4, operating results and notes manner no different.

Fifth, how to select two modes

Two models have different features, notes version for simple and fast mode, in fact, as they are now such a popular micro-service model, a micro-services will correspond to its own database, multi-table join query demand will be greatly reduced, will be more the more fit to this model.

老传统模式比较适合大型项目,可以灵活的动态生成sql,方便调整sql,有的人就是爱写sql,再配上点存储过程,越复杂越好,感觉自己越牛,那你就用这个。

发布了110 篇原创文章 · 获赞 8 · 访问量 6912

Guess you like

Origin blog.csdn.net/guorui_java/article/details/104229009