当前位置:网站首页>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
边栏推荐
- URI, URL and urn difference, relation and syntax diagram
- MySQL related summary
- Detailed explanation of maxpooling corresponding to conv1d, conv2d and conv3d machines of tensorflow2
- How do you use your own data to achieve your marketing goals?
- Jeux de plombiers
- PyFlink实现自定义SourceFunction
- redis
- Redis usage optimization summary learning
- 微服务开发环境搭建
- 水管工游戏
猜你喜欢

Large end storage and small end storage

matplotlib画图中文乱码

Matplotlib drawing Chinese garbled code

MySQL related summary

DFS and BFS notes (II): depth first search (implemented in C language)
![[WSL2]WSL2迁移虚拟磁盘文件ext4.vhdx](/img/e9/4e08e07c2de2f99c2938e79f7f1c44.png)
[WSL2]WSL2迁移虚拟磁盘文件ext4.vhdx

水管工游戏
![[Andoid][踩坑]CTS 11_r3开始出现的testBootClassPathAndSystemServerClasspath_nonDuplicateClasses FAIL问题分析](/img/b5/7ea603775dc0448368d209de037a43.png)
[Andoid][踩坑]CTS 11_r3开始出现的testBootClassPathAndSystemServerClasspath_nonDuplicateClasses FAIL问题分析

30: Kakfa simulates JSON data generation and transmission

What is Google plus large text ads? How to use it?
随机推荐
H5 open the app. If the app is not downloaded, jump to the download page. If the app has been downloaded, wake up the app
受众群体应该选择观察模式还是定位模式?
【官方文件汇总】国科大学位论文撰写规范
开发者来稿|AMD赛灵思中文论坛分享 - 提问的智慧
leetcode743. Network latency (medium, Dijkstra)
Detailed explanation of audience characteristics
[soft test] software designer knowledge points sorting (to be updated)
MySQL performance optimization
Installing pytorch geometric
Traversal of binary tree - first order traversal, middle order traversal, and second order traversal
[learn FPGA programming from scratch -22]: Advanced chapter - Architecture - Design and modeling of FPGA internal hardware circuit
Topic creation and running example of ROS
Cmake has no obvious error after compilation, but prompts that pthread cannot be found
微服务开发环境搭建
Redis usage optimization summary learning
ng-tv-focusable
三、上传织物图片至SQL Server并提供name进行展示织物照片
dfs与bfs解决宝岛探险
The method of drawing rounded panel with Delphi
Reinstall opencv and step on the pit.