The demo style

I sorted out some information, and friends in need can click to get it directly.

Java Basics

22 Java Architect Core books

Learning routes and materials from 0 to 1Java

1000+ questions from 2021

Setup environment (POM file)

Project creation

When creating a project, you should choose Web, Thymeleaf, Mybatis (my side is the mirror of Ali Cloud, so they are All Chinese options, you can take the corresponding seat).

I still need to manually import Thymeleaf after using the image selection of Ali Cloud (there should be no such bug if USING the official website)

Mybatis = mybatis = mybatis = mybatis = mybatis = mybatis = MYbatis = MYbatis = MYbatis

Import dependencies and plug-ins

Rely on

After the project has been created, you need to add the following dependencies (as I mentioned earlier, thymeleaf dependencies may be created as soon as they are created). Here I am using the Druid connection pool, but you can also use the native one (as long as it is in the configuration file).

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> < version > 2.3.7. RELEASE < / version > < / dependency > <! --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> <! -- Database driver --> <! -- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> < artifactId > mysql connector - Java < / artifactId > < version > 5.1.38 < / version > < / dependency >Copy the code

The plug-in

The generator plugin

ConfigurationFile represents the generator configurationFile path (typically placed under resources)

<! Generator --> <plugin> <groupId>org.mybatis. Generator </groupId> < artifactId > mybatis generator - maven plugin - < / artifactId > < version > 1.3.6 < / version > < dependencies > < the dependency > < the groupId > mysql < / groupId > < artifactId > mysql connector - Java < / artifactId > < version > 5.1.38 < / version > < / dependency > </dependencies> <! -- Specify the configuration file path --> < Configuration > <configurationFile>${project.basedir}/src/main/resources/generatorConfig.xml</configurationFile> <verbose>true</verbose>  <overwrite>true</overwrite> </configuration> </plugin>Copy the code

Resource copy plug-in

The Java directory contains mapper XML and resources files. Don’t forget to configure HTML

<! <resources> <resource> <directory> SRC /main/ Java </directory> <includes> **/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.html</include> </includes> </resource> </resources>Copy the code

The configuration file

application.properties

The following comments are some additional configurations for Mybatis (which may be used when not using generator)

spring.datasource.url= jdbc:mysql://localhost:3306/login? useUnicode=true&characterEncoding=utf-8&useSSl=false spring.datasource.driver-class-name= com.mysql.jdbc.Driver spring.datasource.username= root spring.datasource.password= wityy spring.datasource.type= Com. Alibaba. Druid. Pool. DruidDataSource # application service WEB access port # server: # port: 8080 # # # the following configuration is not required for this project # # # The following content is to allow MyBatis to map # specify MyBatis Mapper file # MyBatis: # mapper-locations: # mapper-locations: # mapper-locations: # mapper-locations: # mapper-locations: # -classpath :/mapper/*.xml # resultType set poJO class short, generator plugin generated do not need to configure, if you write to configure # type-aliases-package: cn.wit.springbootmybatis.pojoCopy the code

generatorConfig.xml

If you want to set the DTD, set it in setting

TargetPackage is determined based on the package name in the project

<? The 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> <context id="testTables" targetRuntime="MyBatis3"> <commentGenerator> <! --> <property name="suppressAllComments" value="true"/> </commentGenerator> <! Database connection information: Driver, connection address, user name, password - > < jdbcConnection driverClass = ". Com. Mysql. JDBC Driver "connectionURL =" JDBC: mysql: / / localhost: 3306 / login"  userId="root" password="wityy" ></jdbcConnection> <! -- Default false, Parse JDBC DECIMAL and NUMERIC types to Integer NUMRIC types to java.math.BigDecimal--> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <javaModelGenerator targetPackage="cn.wit.springbootmybatis.pojo" targetProject=".\src\main\java"> <! Property name="enableSubPackages" value="false"/> <! <property name="trimStrings" value="true"/> </javaModelGenerator> <! -- targetProject mapper mapping file generated by the position - > < sqlMapGenerator targetPackage = "cn. Wit. Springbootmybatis. Mapper" targetProject=".\src\main\java"> <! <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.wit.springbootmybatis.mapper" targetProject=".\src\main\java"> <! <property name="enableSubPackages" value="false"/> </javaClientGenerator> <table tableName="flower"></table> </context> </generatorConfiguration>Copy the code

After configuring the Generator and generating the POJO and Mapper, Maven double-click the red box

The structure is then generated, and you can see that there is a FlowerExample that sets the qualification.

Start the function

Add @ MapperScan (” cn. Wit. Springbootmybatis. Mapper “) annotation

@ SpringBootApplication @ MapperScan (cn. Wit. Springbootmybatis. "mapper") / / specified scanning interface and mapping configuration file package name public class SpringbootmybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringbootmybatisApplication.class, args); }}Copy the code

service

Public interface FlowerService {// Add a void addFlower(Flower Flower); // Delete a void delFlower(int id); List<Flower> selAllFlower(); Void updPriceFlower(Flower Flower); // UpdateFlower preUpdateFlower(int id); }Copy the code

When querying, selectByExample takes example as an argument to indicate all queries (example.createcriteria ().andNameequalto (name) if you want to add a qualification; Set exmple = exmple = exmple = exmple

Compared with my article that did not integrate Mybatis, the update logic of that article is to pass ID and price, and only change the data price corresponding to the ID. The logic of this article is slightly changed, that is, to get the whole data through the ID, change the data price, This data is then updated to the database (this is more appropriate for generator use as the updateByPrimaryKey method updates the entire data by ID rather than a single property, although this could also be done by Example)

@Service public class FlowerServiceImpl implements FlowerService { @Autowired FlowerMapper flowerMapper; @Override @Transactional public void addFlower(Flower flower) { this.flowerMapper.insert(flower); } @Override @Transactional public void delFlower(int id) { this.flowerMapper.deleteByPrimaryKey(id); } @Override public List<Flower> selAllFlower() { FlowerExample example=new FlowerExample(); return this.flowerMapper.selectByExample(example); } @Override @Transactional public void updPriceFlower(Flower flower) { this.flowerMapper.updateByPrimaryKey(flower); } @Override public Flower preUpdateFlower(int id) { return this.flowerMapper.selectByPrimaryKey(id); }}Copy the code

Controller

PageController

Page hops, they match other urls first, and when they don’t match, they match this, and they think it’s an HTML page request

@controller public class PageController {/** ** PageController */ @requestMapping ("/{page}") public String showPage(@PathVariable("page") String page){ return page; }}Copy the code

FlowerController

@Controller @RequestMapping("flower") public class FlowerController { @Autowired private FlowerService flowerService; * */ @requestMapping ("/addFlower") public String addFlower(Flower Flower, HttpServletRequest request){ try { this.flowerService.addFlower(flower); // add the flower to return "redirect:/flower/show"; }catch (Exception e){return "error"; * */ @requestMapping ("/delFlower/{id}") public String delFlower(@pathvariable int id, @pathvariable int id) HttpServletRequest request){ try { this.flowerService.delFlower(id); return "redirect:/flower/show"; }catch (Exception e){ return "error"; * */ @requestMapping ("/show") public String selAllFlower(HttpServletRequest Request){try {List<Flower> list = this.flowerService.selAllFlower(); request.setAttribute("flowers",list); return "main.html"; }catch (Exception e){ return "error.html"; }} / update process * / * * * @ RequestMapping ("/updPriceFlower ") public String updPriceFlower (Flower Flower, it request){ try { Flower flower1=this.flowerService.preUpdateFlower(flower.getId()); flower1.setPrice(flower.getPrice()); this.flowerService.updPriceFlower(flower1); return "redirect:/flower/show"; }catch (Exception e){e.printStackTrace(); return "error"; }} /* * * Pre-updated, ready to jump to the updFlower interface, UpdPriceFlower */ @requestMapping ("/update/{id}") public String update(@pathVariable int id, HttpServletRequest request){ try { request.setAttribute("id",id); return "updFlower"; }catch (Exception e){ return "error"; }}}Copy the code

thymeleaf

error

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>ERROR</h1> ERROR </body> </html>Copy the code

main

<! DOCTYPE html> <html lang="en"> <html xmlns:th="http://www.thymeleaf.org"> <link rel="shortcut icon" href=".. /resources/favicon.ico" th:href="@{/static/favicon.ico}"> <head> <meta charset=" utF-8 "> <title> The < body > < table border = "1 px" > < tr > < th > id < / th > < th > flower < / th > < th > price < / th > < th > of < / th > < th > price update < / th > < th > delete < / th > < / tr > < tr th:each="flower : ${flowers}"> <td th:text="${flower.id}"></td> <td th:text="${flower.name}"></td> <td th:text="${flower.price}"></td> <td Th: text = "${flower. Production}" > < / td > < td > < a th: href = "@ {/ flower/update / {id} / (id = ${flower. Id})}" > update < / a > < / td > < td > < a Th: href = "@ {/ flower/delFlower / {id} / (id = ${flower. Id})}" > delete < / a > < / td > < / tr > < / table > < br > < br > add < flowers form Th :action="@{/flower/addFlower}" method="get"> Enter name<input type="text" value="" name="name"><br> Enter unit price <input type="text" Value =" name="price"><br> Input type="text" value=" name="production"><br> < form type="submit" value=" submit" > </form> </body> </html>Copy the code

updFlower

<! DOCTYPE html> <html lang="en"> <html xmlns:th="http://www.thymeleaf.org"> <link rel="shortcut icon" href=".. /resources/favicon.ico" th:href="@{/static/favicon.ico}"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/flower/updPriceFlower" method="get"> Please enter the updated price <input type="text" name="price"><br> <input Type = "hidden" name = "id" th: value = "${id}" > < input type = "submit" value = "submit" > < / form > < / body > < / HTML >Copy the code