“Offer comes, ask friends to take it! I am participating in the 2022 Spring Recruit Punch card campaign. Click here for more details.”

Spring Boot integration MyBatis

Automatic configuration of MyBatis

Create project Spring-boot-Mybatis, select MyBatis Framework when creating project will automatically introduce myBatis Starter

Analyze Mybatis’ Staters launcher dependencies

MyBatis automatic configuration classes and configuration items are under the autoconfigure package

The MyBatis automatic configuration class relies on the SqlSessionFactory and SqlSessionFactoryBean classes as well as the DataSource class, and enables the properties of MyBatisProperties as configuration items. And in DataSourceAutoConfiguration automatically configure classes and class MybatisLanguageDriverAutoConfiguration will only take effect after effect.

MyBatisProperties class source code contains myBatis configuration items

Configuration prefixes for MyBatis all start with MyBatis

Configure the Druid data source

The introduction of driud

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.8</version>
</dependency>
Copy the code

Spring Boot 2.6.4 (4) – Data Access (Part A JDBC)

Initialize the project

Place the employee. SQL and department. SQL files in the Resources directory

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lastName` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `gender` int(2) DEFAULT NULL,
  `d_id` int(11) DEFAULT NULL.PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Copy the code
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `departmentName` varchar(255) DEFAULT NULL.PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Copy the code

Create two entity classes Employee and Department in the Entity directory for the Employee table and Department table

@Data
public class Employee {

    private Integer id;
    private String lastName;
    private String email;
    private Integer gender;
    private Integer dId;
}
Copy the code
@Data
public class Department {

    private Integer id;
    private String departmentName;
}
Copy the code

Configure a custom data source initialization class to initialize the data source

@Configuration
public class LilithDataSourceInitializer {

    @Value("classpath:employee.sql")
    private Resource employee;

    @Value("classpath:department.sql")
    private Resource department;

    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource){
        final DataSourceInitializer initializer = new DataSourceInitializer();

        initializer.setDataSource(dataSource);
        initializer.setDatabasePopulator(databasePopulator());
        return initializer;
    }

    private DatabasePopulator databasePopulator(a){
        final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScripts(employee,department);
        returnpopulator; }}Copy the code

The @Configuration annotation can be commented out if you don’t want to initialize the data before starting the application again

Second, the use of MyBatis annotation method

Create the DepartmentMapper interface to annotate SQL statements with annotations

@Mapper
public interface DepartmentMapper {

    @Select("SELECT * FROM department WHERE id = #{id}")
    Department selectOneById(Integer id);

    @Delete("DELETE FROM department WHERE id = #{id}")
    void deleteOneById(Integer id);

    @Insert("INSERT INTO department (department_name) VALUES (#{departmentName})")
    void insert(Department department);

    @Update("UPDATE department SET department_name = #{departmentName} where id = #{departmentId}")
    void update(Department department);
}
Copy the code

Create the DepartmentMapperTest test class to test the add, delete, change and check methods in DepartmentMapper

@SpringBootTest
public class DepartmentMapperTest {

    @Resource
    private DepartmentMapper departmentMapper;

    @Test
    public void selectOneById(a) {
        Department department = departmentMapper.selectOneById(1);
        System.out.println(department);
    }

    @Test
    public void insert(a) {
        Department department = new Department();
        department.setDepartmentName("Avengers"); departmentMapper.insert(department); }}Copy the code

Test insert method

Test the selectOneById method

MyBatis is configured with camel name conversion

Alter table departmentName to underscore department_name; The selectOneById method is executed again

When the DepartmentName property is queried as empty, you can turn on the hump naming conversion in the YML configuration file

mybatis:
  configuration:
    map-underscore-to-camel-case: true
Copy the code

The specified data can be queried again

Configuration class enables the hump naming conversion

You can also use configuration classes to enable camel naming transformations. MyBatisAutoConfuguration includes the configurationCustomizers property, which is a List of all custom configurationsThe ConfigurationCustomizer interface has a Customize method that passes in a Configuration custom Configuration

Properties in the Configuration class are customizable configurations

Create a New LilithMyBatisConfig config class under the Config package and add a configurationCustomizer method. Inject the configurationCustomizer implementation class that sets the properties into the container

@Configuration
public class LilithMyBatisConfig {
    
    @Bean
    public ConfigurationCustomizer configurationCustomizer(a){
        return configuration -> configuration.setMapUnderscoreToCamelCase(true); }}Copy the code

Lambda expressions are used here to implement the Customize method in the ConfigurationCustomizer interface

Annotate the transformation of the hump name in the YML file and re-execute the selectOneById method

The data can be queried successfully.

@ Mapper annotations

The @mapper annotation is key to automatic configuration. It marks the current class as a component of the container, and will not start without the @mapper annotation.

When there are a lot of Mapper interfaces, adding @Mapper annotations to each Mapper interface is cumbersome. You can use the @Mapperscan annotation on the main startup class to scan all Mapper interfaces

3. Use of MyBatis configuration file

EmployeeMapper: @mapper or @mapperscan annotations are required to use MyBatis as annotations or configuration files.

@Mapper
public interface EmployeeMapper {

    void insert(Employee employee);

    Employee selectOneById(Integer id);
}
Copy the code

Create the mappers folder under the Resources directory, add the employeemapper. XML file, and add the SQL statements corresponding to the selectOneById and INSERT methods in the Mapper interface


      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lilith.mybatis.mapper.EmployeeMapper">

    <select id="selectOneById" resultType="com.lilith.mybatis.entity.Employee">
        select * from employee where id = #{id}
    </select>

    <insert id="insert" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
        INSERT INTO employee (last_name, email, gender, d_id)
        VALUES (#{lastName}, #{email}, #{gender},#{dId})
    </insert>
    
</mapper>
Copy the code

Added mybatis configuration to YML

mybatis:
  Location of the global configuration file
  config-location: classpath:mybatis-config.xml
  mapper-locations: classpath:mappers/*.xml
  configuration:
    map-underscore-to-camel-case: true
Copy the code

Write test class

@SpringBootTest
public class EmployeeMapperTest {

    @Resource
    private EmployeeMapper employeeMapper;

    @Test
    public void insert(a) {
        Employee employee = new Employee();
        employee.setLastName("Thanos");
        employee.setEmail("[email protected]");
        employee.setGender(1);
        employee.setDId(1);

        employeeMapper.insert(employee);
    }


    @Test
    public void selectOneById(a) {

        Employee employee = employeeMapper.selectOneById(1); System.out.println(employee); }}Copy the code

Perform insert methodError Config-location and configuration cannot be written to the yML file at the same time. Create a new MyBatis global configuration file in the Resources directory and add configuration to the MyBatis -config. XML global configuration file


      
<! DOCTYPEconfiguration
        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>
Copy the code

Run the test again

The console shows that 1 row was successfully updated and the data was successfully inserted into the input sentence cool table

Execute the selectOneById method

The data inserted by the INSERT method was successfully queried