This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

preface

For The Java system, the most famous ORM framework is Mybatis,JPA,Hibernate, in the face of rapid iteration of leadership development scenario, most of the projects are based on SSM, this M is Mybatis.

Mybatis simple and flexible from another point of view is the need to write all the code (simple can use the code generator),MybatisPlus is Mybatis enhancement tool, on the basis of Mybatis only enhance without change, to simplify the development and improve efficiency.

Mybatis-Plus is available here

integration

The connection pool used here is the default HikariCP connection pool. If you want to use Druid or just Mybatis, see another article

<! --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <! --Mbatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> The < version > 2.1.1 < / version > < / dependency > <! --Mbatis Plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> < version > 3.3.1. TMP < / version > < / dependency >Copy the code

Application. Yml configuration

Database and connection pool configuration

Spring: datasource: driver-class-name: com.mysql.cj.jdbc.driver #mysql 8.0 url: JDBC :mysql:///zdc_test? useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE&serverTimezone=GMT%2B8&useSSL=fa lse&allowPublicKeyRetrieval=true username: root password: 123123 type: Com. Zaxxer. Hikari. HikariDataSource # currently used data source hikari hikari: minimum - idle: 10 maximum-pool-size: 10 10 maximum-pool-size: 10 auto-commit: true 600, 000 # Specifies the maximum lifetime of a connection to be idle. If the connection expires, it will be released. Default :10 minutes max-lifetime: Default :30 minutes. Use mysql-connection-timeout to set this parameter to 30 seconds less than the database timeout. 30000 # Maximum number of milliseconds to wait for a connection to be allocated from the connection pool. If a connection is not available, SQLException occurs. Default :30 seconds connection-test-query: select 1 Read -only: false # If it is read-onlyCopy the code

MyBatis configuration

MybatisPlus configuration (official documentation: MyBatis configuration is configurable on mybatisPlus)

mybatis-plus: mapper-locations: classpath:/mappers/*Mapper.xml type-aliases-package: Entity configuration: use-generated-keys: true global-config: db-config: id-type: auto # Primary key auto-incrementCopy the code

Necessary annotation configuration

Add annotations to the Application startup class

@ComponentScan({"zdc.enterprise.*"}) @EnableTransactionManagement @MapperScan("zdc.enterprise.mapper") @SpringBootApplication public class SpringBootEnterpriseApplication { public static void main(String[] args) { SpringApplication.run(SpringBootEnterpriseApplication.class, args); }}Copy the code

@ EnableTransactionManagement is transaction management

@mapperscan is the scanning path of the configuration DAO layer interface file, that is, the XXMapper or XXDao path corresponding to XML

use

Project directory structure

(1) Create one in the databasestudenttable

CREATE TABLE `student` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `info` varchar(255)  COMMENT 'zouzdc',
  `del_flag` tinyint(1) DEFAULT NULL,
 `create_time` datetime,
 `create_by` varchar(255),
 `update_time` datetime ,
 `update_by` varchar(255),
 PRIMARY KEY (`id`)
) ;
Copy the code

(2) inentityPackage created underStudent.javaclass

@Data @NoArgsConstructor public class Student { /** * id */ @TableId private Long id; /** * other information */ private String info; 0 No 1 Yes */ @TABLelogic private String delFlag; /** * create Date */ @tableField (fill = FieldFill.INSERT) private Date createTime; /** * creator */ @tableField (fill = FieldFill.INSERT) private String createBy; /** * update Date */ @tableField (fill = FieldFill.INSERT_UPDATE) private Date updateTime; /** */ @tableField (fill = FieldFill.INSERT_UPDATE) private String updateBy; }Copy the code

(3) controllerlayer

StudentService provides an example of the built-in methods

@RestController @RequestMapping("/student") public class StudentController { @Autowired(required = false) public StudentService studentService; @getMapping ("getById") public R getStudentById(Student Student){// Add studentService.save(Student); / / change studentService updateById (student); Student = studentService.getById(student.getid ()); / / delete studentService removeById (student getId ()); / / List < Student > zouzdc = studentService. LambdaQuery (). The eq (Student: : getInfo, "zouzdc"). The List (); return R.success(); }}Copy the code

(4) serviceLayer, need inheritanceIServiceOr implementationServiceImplCommon interface

The service interface StudentService. Java

public interface StudentService extends IService<Student> {
}
Copy the code

Service Implementation class studentService.java

@Service @Slf4j public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {// studentMapper is not declared studentMapper. BaseMapper is studentMapper @autoWired (required =) false) private StudentMapper studentMapper; Public void savePlus(Student vo) {Student one = this.getById(vo.getid ()); Student student = baseMapper.selectById(vo.getId()); }}Copy the code

(4)MapperLayers need to inheritBaseMapperinterface

public interface StudentMapper extends BaseMapper<Student> {
}
Copy the code

(5)resourcesthemappersFile creationStudentMapper.xmlFile, same as native

<? The 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="zdc.enterprise.mapper.StudentMapper"> </mapper>Copy the code

note

Weigh whether or not to use native MyBatis based on project needs

When using MyBatis or Using MyBatis-Plus, you must use the code generator. Many open source code generators on the Internet can also write code templates to improve efficiency

If you use IDEA, it is recommended to use free Mybatis plugin or MybatisX plug-in, which can automatically associate interface classes with Mapper files and jump directly

See the next article for more details on how to use it

Source: author: ZOUZDC links: https://juejin.cn/post/7028963866063306760 re the nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code