当前位置:网站首页>Restful interface specification annotation of pringboot (2)
Restful interface specification annotation of pringboot (2)
2022-06-13 01:44:00 【I love to enjoy】
1,springboot reverse mybatis Generate interface classes
pom Dependency package
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
pom Dependent plug-ins
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
generator.properties The configuration file
jdbc.driverLocation=D:/mysql-connector-java-8.0.16.jar
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://localhost:3306/test
jdbc.userId=root
jdbc.password=root
generatorConfig.xml file
| javaModelGenerator | Path of module generation | |
|---|---|---|
| sqlMapGenerator | Mapper The directory where the mapping file is generated Generate the corresponding... For each database table SqlMap file , Generally refers to resource So let's make a new one mapper In the folder | targetProject="src/main/resource"> |
| javaClientGenerator | Mapper Interface file path | targetProject="src/main/java" type="XMLMAPPER"> |
| table | Database table name |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- Import property configuration -->
<properties resource="generator.properties"></properties>
<!-- Specify... For a specific database jdbc drive jar The location of the package -->
<classPathEntry location="${jdbc.driverLocation}"/>
<context id="default" targetRuntime="MyBatis3">
<!-- optional, Designed to create class when , Control comments -->
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--jdbc Database connection to -->
<jdbcConnection
driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.connectionURL}"
userId="${jdbc.userId}"
password="${jdbc.password}">
<!--MySQL I won't support it schema perhaps catalog So you need to add this -->
<!-- Otherwise, the generator will generate the same name tables of other databases -->
<!-- The phenomenon is that there are fields in a class that are not in the database table -->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- Non essential , Type processor , In database type and java Conversion control between types -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- Model Model generator , Used to generate a primary key key Class , Record class And inquiry Example class
targetPackage Specify the generated model The package name where the generation is located
targetProject Specify the path under the project
-->
<javaModelGenerator targetPackage="com.example.test001.bean"
targetProject="src/main/java">
<!-- Whether to allow subpackages , namely targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- Whether the model add to Constructors -->
<property name="constructorBased" value="true"/>
<!-- Whether to class CHAR Type of column data to proceed with trim operation -->
<property name="trimStrings" value="true"/>
<!-- The establishment of a Model Is the object It can't be changed That is generated Model The object will not have setter Method , Only the construction method -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!--Mapper The directory where the mapping file is generated Generate the corresponding... For each database table SqlMap file -->
<sqlMapGenerator targetPackage="mapper"
targetProject="src/main/resource">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- Client code , Generate easy to use targets for Model Objects and XML The configuration file Code for
type="ANNOTATEDMAPPER", Generate Java Model And annotation based Mapper object
type="MIXEDMAPPER", Generate annotation based Java Model And corresponding Mapper object
type="XMLMAPPER", Generate SQLMap XML Documents and independent Mapper Interface
-->
<javaClientGenerator targetPackage="com.example.test001.mapper"
targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- Tables to reverse engineer -->
<table tableName="user" />
<!-- <table tableName="category" />-->
</context>
</generatorConfiguration>
```
2, perform generator Generate interface classes
1, The console uses mvn command :
mvn mybatis-generator:generate
2, double-click mvn Inside pulgins Under plug-in renerator Start the plug-in

Three files will be generated after the execution

3, Create a controller
| annotation | explain | Example |
|---|---|---|
| @RestController | Add annotations to the class , It is equivalent to adding... To a class @Controller And add... To the method @ ResponseBody Two - , Add... To the class @RestController After annotation, you do not add... To each method @ResponseBody Note the | @RestController public class StudentController {} |
| @Autowired | Automatically inject annotated objects | @Autowired private StudentService studentService; |
| @GetMapping | get Requested comment , amount to @RequestMapping(value = "/get",method = RequestMethod.GET), hinder port,put,delete The usage is the same | @GetMapping(value = "/get/{id}") |
| @PathVariable | Path variable , Identify the variables above the annotations , Such as "/get/{id}",id Variables can be identified by this annotation | public Object getName(@PathVariable( "id") Integer id){} |
| @PathParam | Define a parameter , Without this annotation , The default value is the variable name of the formal parameter | public Object inster( @PathParam("name") String name){} |
```
package com.springboot.test002.web;
import com.springboot.test002.model.Student;
import com.springboot.test002.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.websocket.server.PathParam;
import java.util.HashMap;
/**
* restfull Interface case , Connect to the database to add, delete, and correct errors
*/
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping(value = "/get/{id}")
public Object getName(@PathVariable( "id") Integer id){
HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
objectObjectHashMap.put("id",id);
return objectObjectHashMap;
}
@PostMapping(value = "/inster")
public Object inster(
@PathParam("name") String name,
@PathParam("age") Integer age,
@PathParam("passwod") String password){
HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
objectObjectHashMap.put("name",name);
objectObjectHashMap.put("age",age);
objectObjectHashMap.put("passwod",password);
int i = studentService.inster(objectObjectHashMap);
return i ;
}
@PutMapping(value = "/update/{id}")
public Object update(@PathVariable("id") Integer id,
@PathParam("name") String name,
@PathParam("age") Integer age,
@PathParam("password") String password){
Student student = new Student();
student.setId(id);
student.setName(name);
student.setAge(age);
student.setPasswod(password);
int i = studentService.update(student);
return i ;
}
@DeleteMapping(value = "/delete/{id}")
public Object delete(
@PathVariable( "id") Integer id){
Student student = new Student();
student.setId(id);
return studentService.delete(student.getId());
}
@RequestMapping(value = "/getUser")
public Object get(Integer id){
Student student = new Student();
student.setId(id);
return studentService.get(student.getId());
}
}
4,application Profile add import mapper Of xml route
Appoint resource The next path mapper All under xml file
mybatis:
mapper-locations: classpath:mapper/*.xml
Complete configuration file
# Application service WEB Access port
server:
port: 8081
servlet:
context-path: /
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/student?serverTimezone=GMT%2B8&&characterEncoding=utf8
password: root
username: root
redis:
password: 123456
host: 127.0.0.1
port: 6379
mybatis:
mapper-locations: classpath:mapper/*.xml
5, Execution effect

6, Test code address
https://github.com/redesperado/SpringBoot
This article permanently updates the address :
https://www.fenxiangbe.com/p/pringboot And restfull Interface specification notes ( Two ).html
边栏推荐
- The method of drawing rounded panel with Delphi
- 一种不带CPU的DPU架构:Hyperion
- Golang context (context summary)
- Torch. Distributions. Normal
- Introduction to ROS runtime
- Summary of various installation methods of Lab View
- 五、库存查询功能的完善
- Reinstall opencv and step on the pit.
- Developer contributions amd Xilinx Chinese Forum sharing - wisdom of questioning
- How many smart bids does Google have?
猜你喜欢

About tkinter Canvas does not display pictures

DFS and BFS notes (II): depth first search (implemented in C language)

Developer contributions amd Xilinx Chinese Forum sharing - wisdom of questioning

A DPU architecture without CPU: Hyperion

MySQL connection query

谷歌加大型文字广告是什么?怎么用?

How to solve practical problems through audience positioning?

三、上传织物图片至SQL Server并提供name进行展示织物照片

My crawler learning notes

五、库存查询功能的完善
随机推荐
[MySQL password management] - [administrator password known, unknown (forgotten), cracked]
Server installation jupyterab and remote login configuration
What is the path field—— Competitive advertising
Detailed explanation of deep learning parameter adjustment skills
About the proposed signature file migration to industry standard format pkcs12
Numpy multidimensional array transpose transpose
Project training (XVII) -- personal work summary
Golang context (context summary)
【软考】软件设计师知识点整理(待更新)
TensorFlow 2. X multi graphics card distributed training
[从零开始学习FPGA编程-22]:进阶篇 - 架构 - FPGA内部硬件电路的设计与建模
Phaser3 load
How many times does the constructor execute?
Stack stack LIFO
Set and array conversion, list, array
Anims of phaser3
How to solve practical problems through audience positioning?
V-inline-date, similar to Ctrip, flying pig, time selection with price
机器学习基础 SVM(支持向量机)
PyFlink实现自定义SourceFunction