Spring Boot integrated mybatis for Universal mapper

Source: Internet
Author: User
Tags app service

Preface

MyBatis
About MyBatis, most people are familiar with it. MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code and manually sets parameters and gets the result set. MyBatis can use simple XML or annotations to configure and map native information, mapping interfaces and Java POJOs (Plain old Java Objects, ordinary Java objects) to records in a database.
Whether DDD (domain driven Design, domain-driven modeling) or hierarchical architecture, it involves the operation of the database persistence layer, this article will explain how the spring boot integration MyBatis implements the generic Mapper.
Spring Boot Integrated MyBatis
Introducing Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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>1.3.1</version>    </dependency>    <dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>    </dependency>    <dependency>        <groupId>org.projectlombok</groupId>        <artifactId>lombok</artifactId>    </dependency>    <dependency>        <groupId>com.zaxxer</groupId>        <artifactId>HikariCP</artifactId>    </dependency>

The copy code can be seen as above about MyBatis introduction of Mybatis-spring-boot-starter, provided by MyBatis starter.
Database Configuration
In Application.yml, add the following configuration:
Spring
DataSource
Hikari
Connection-test-query:select 1
Minimum-idle:1
Maximum-pool-size:5
Pool-name:dbcp1
Driver-class-name:com.mysql.jdbc.driver
url:jdbc:mysql://localhost:3306/test?autoreconnect=true&usessl=false&useunicode=true& Characterencoding=utf-8
Username:user
Password:pwd
Type:com.zaxxer.hikari.HikariDataSource
Schema[0]: Classpath:/init.sql
Initialize:true
Copy the code to see that we have configured the basic information of the Hikari and the database. The SQL script under Classpath is automatically initialized when the app service starts.
CREATE TABLE IF not EXISTStest(
idbigint (unsigned) not NULL,
local_namevarchar (+) is not NULL,
PRIMARY KEY (id)
) Engine=innodb DEFAULT Charset=utf8;
Copy the code in the SQL script, we created a test table.
Here, we generally need to configure the path of the XML file and entity class for the mybatis mapping. Generate code automatically based on MyBatis generator. including Xxmapper.java,xxentity.java, Xxmapper.xml. Here we do not demonstrate, directly into the next step of the general mapper implementation.
Use of universal Mapper
Introducing Dependencies
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.0</version>
</dependency>
Copy Code General Mapper, author of abel533, is interested to read the source.
Configuring Universal Mapper
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import Tk.mybatis.spring.mapper.MapperScannerConfigurer;

Import java.util.Properties;

@Configuration
public class Mybatismapperscannerconfig {br/> @Bean
Mapperscannerconfigurer mapperscannerconfigurer = new Mapperscannerconfigurer ();
Mapperscannerconfigurer.setsqlsessionfactorybeanname ("Sqlsessionfactory");
Mapperscannerconfigurer.setbasepackage ("Com.blueskykong.mybatis.dao");//Scan DAO under this path
Properties properties = new Properties ();
Properties.setproperty ("Mappers", "Com.blueskykong.mybatis.config.BaseDao");//General DAO
Properties.setproperty ("Notempty", "false");
Properties.setproperty ("IDENTITY", "MYSQL");
Mapperscannerconfigurer.setproperties (properties);
return mapperscannerconfigurer;
}
}
Copy code in the configuration, the DAO under the specified path is set, and a generic DAO is specified. It is important to note that the mapperscannerconfigurer comes from the Tk.mybatis.spring.mapper package.
Basedao
Import tk.mybatis.mapper.common.Mapper;
Import Tk.mybatis.mapper.common.MySqlMapper;

Public interface Basedao<t> extends mapper<t>,mysqlmapper<t>{

}br/> Copy Code Generic Mapper interface, other interfaces inherit the interface.
Create entity
We need to add the entity corresponding to the test table.
@Data
@AllArgsConstructor

public class Testmodel {

@Id@Column(name = "id")@GeneratedValue(strategy = GenerationType.IDENTITY)private Integer id;private String localName;

}
Copy the code where the @Table (name = "Test") annotation specifies the database table name corresponding to the entity.
Configuration file
MyBatis
Configuration
Map-underscore-to-camel-case:true
Copy code in order to better map Java entities and database fields, we specify the mapping configuration for the underscore hump method.
Testdao Writing
Public interface Testdao extends basedao<testmodel> {

@Insert("insert into test(id, local_name) values(#{id}, #{localName})")Integer insertTestModel(TestModel testModel);

}
The copy code Testdao inherits from Basedao and specifies that the generic is the corresponding Testmodel. The Testdao contains inherited methods, such as:
int Deletebyprimarykey (Integer userId);

int insert(User record);int insertSelective(User record);User selectByPrimaryKey(Integer userId);int updateByPrimaryKeySelective(User record);int updateByPrimaryKey(User record);

The copy code can also customize some methods, and we have customized a Inserttestmodel method above.
Service Layer and Control layer
This article is slightly over these two layers, it is relatively simple, the reader can refer to the corresponding source address in this article.
Result validation
After inserting a piece of data, we query the corresponding entity. The results of the corresponding execution are also successful, and you can see the following log information for the console:
C.b.mybatis.dao.testdao.inserttestmodel: ==> preparing:insert into Test (ID, Local_name) VALUES (?,?)
C.b.mybatis.dao.testdao.inserttestmodel: ==> parameters:5953 (Integer), testname (String)
C.b.mybatis.dao.testdao.inserttestmodel: <== updates:1
C.b.m.dao.testdao.selectbyprimarykey: ==> preparing:select id,local_name from test WHERE id =?
C.b.m.dao.testdao.selectbyprimarykey: ==> parameters:5953 (Integer)
C.b.m.dao.testdao.selectbyprimarykey: <== total:1
Copy Code spring Boot Integration MyBatis Implementation General Mapper that's it.

Summary

MyBatis is a very common component of the persistence layer, and the Spring boot Advocacy convention is better than configuration, especially for many XML configurations. Of course, many students use Spring Data. In comparison, I think MyBatis's SQL is more flexible than spring data, as the specific comparison is not discussed here.

Spring Boot integrated mybatis for Universal mapper

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.