Spring Boot 整合Spring MVC 過程css
關係圖:
這種關係圖的程序代碼的書寫代碼的順序是從右邊往左邊寫!
要理解Spring MVC 的操做理解:
作這些用到了mybatis 的整合,這樣簡化了jdbc鏈接數據庫的操做
下面是書寫的代碼:
-- Application.propertieshtml
spring.main.banner-mode=offjava
spring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=rootmysql
mybatis.mapper-locations=classpath:/mapper/goods/GoodsMapper.xmlweb
logging.level.com.cy=debugspring
server.port=80
server.servlet.context-path=/binbinsql
spring.thymeleaf.prefix=classpath:/templates/pages/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
--GoodsMapper.xml
<?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="com.cy.pj.goods.dao.GoodsDao">
<delete id="deleteObjects">數據庫
delete from tb_goods where id in <!-- (1,2,3,4,5) --> <foreach collection="ids" open="(" close=")" separator="," item="id"> #{id} </foreach>
</delete>
</mapper>
Goods.java
package com.cy.pj.goods.pojo;apache
import java.util.Date;api
public class Goods {
private Long id;//id bigint primary key auto_increment private String name;//name varchar(100) not null private String remark;//remark text private Date createdTime;//createdTime datetime public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } @Override public String toString() { return "Goods [id=" + id + ", name=" + name + ", remark=" + remark + ", createdTime=" + createdTime + "]"; }
}
GoodsDao(interface)
package com.cy.pj.goods.dao;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
/*
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.cy.pj.goods.pojo.Goods;
@Mapper
public interface GoodsDao {
@Select("select * from tb_goods") List<Goods>findGoods(); /** * 基於id執行商品信息的刪除, 在mybatis中假如sql映射比較簡單 * 能夠直接以註解方法進行定義 * @param id * @return */ /** * 基於id去查找商品信息 * @param id * @return */ @Select("select * from tb_goods where id=#{id}") Goods findById(Integer id); @Update("update tb_goods set name=#{name},remark=#{remark} where id=#{id}") int UpdateGoods(Goods goods); @Delete("delete from tb_goods where id=#{id}") int deleteById(Integer id); /** * 基於多個id執行商品刪除業務操做 * ids可變參數,用於接受傳入的商品id值 */ int deleteObjects(@Param("ids")Integer...ids); @Insert("insert into tb_goods(name,remark,createdTime) values (#{name},#{remark},now())" ) int insertGoods(Goods goods);
}
GoodsService(interface)
package com.cy.pj.goods.service;
import java.util.List;
import com.cy.pj.goods.pojo.Goods;
/**
*
*/
public interface GoodsService {
Goods findById(Integer id); List<Goods>findGoods(); int deleteById(Integer id); int saveGoods(Goods goods); int UpdateGoods(Goods goods);
}
GoodsServiceImpl
package com.cy.pj.goods.service.impl;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
*/
import org.springframework.stereotype.Service;
import com.cy.pj.goods.dao.GoodsDao;
import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;
//@Deprecated
@Service//是一個特殊的@Component 也能夠用@Component
public class GoodsServiceImpl implements GoodsService{
private static final Logger log = LoggerFactory.getLogger(GoodsServiceImpl.class); @Autowired private GoodsDao goodsdao; @Override public List<Goods> findGoods() { return goodsdao.findGoods(); } @Override public int saveGoods(Goods goods) { // TODO Auto-generated method stub goods.setCreatedTime(new Date()); return goodsdao.insertGoods(goods); } @Override public int deleteById(Integer id) { long t1 = System.currentTimeMillis(); int rows = goodsdao.deleteById(id); long t2 = System.currentTimeMillis(); log.info("deleteById execute time : {}",(t2-t1)); System.out.println(log.getClass().getName()); return rows; } @Override public Goods findById(Integer id) { return goodsdao.findById(id); } @Override public int UpdateGoods(Goods goods) { // TODO Auto-generated method stub return goodsdao.UpdateGoods(goods); }
}
GoodsController
/**
*/
package com.cy.pj.goods.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;
/**
*
*/
@Controller
@RequestMapping("/goods/")
public class GoodsController {
//http://localhost/goods/doDeleteById?id=12 @Autowired private GoodsService goodsService; //執行刪除操做 @RequestMapping("doDeleteById/{id}") public String doDeleteById(@PathVariable Integer id) { goodsService.deleteById(id); return "redirect:/goods/doGoodsUI"; } @RequestMapping("doGoodsAddUI") public String doGoodsAddUI() { return "goods-add"; } @RequestMapping("doGoodsUI") public String doGoodsUI(Model model) { List<Goods> list = goodsService.findGoods(); model.addAttribute("goods", list); return "goods";//view name } @RequestMapping("doSaveGoods") public String doSaveGoods(Goods goods){ goodsService.saveGoods(goods); return "redirect:/goods/doGoodsUI" ; } @RequestMapping("doUpdateGoods") public String doUpdateGoods(Goods goods){ goodsService.UpdateGoods(goods); return "redirect:/goods/doGoodsUI" ; } @RequestMapping("doFindById/{id}") public String doFindById(@PathVariable Integer id,Model model) { Goods goods = goodsService.findById(id); model.addAttribute("goods", goods); return "goods-update"; } //FAQ? //返回的viewname會給誰?誰調用doGoodsController就給誰(DispatcherServelt) //誰負責解析viewname V //解析到的結果會響應到哪裏 }
goods.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>The Goods Page</h1>
添加商品
id | name | remark | createdTime | operation | |
---|---|---|---|---|---|
1 | AAAAAAA | AA.... | 2020/08/31 | delete | update |
</body>
</html>
goods-add.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
ul li {list-style-type: none}
</style>
</head>
<body>
<h1>The Goods Add page</h1> <form th:action="@{/goods/doSaveGoods}" method="p"> <ul> <li>name: <li><input type="text" name="name"> <li>remark: <li><textarea rows="3" cols="30" name="remark"></textarea> <li><input type="submit" value="Save Goods"> </ul> </form>
</body>
</html>
goods-update.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
ul li {list-style-type: none}
</style>
</head>
<body>
<h1>The Goods Add page</h1> <form th:action="@{/goods/doUpdateGoods}" method="p"> <input type="hidden" name="id" th:value="${goods.id}"> <ul> <li>name: <li><input type="text" name="name" th:value="${goods.name}"> <li>remark: <li><textarea rows="3" cols="30" name="remark" th:text="${goods.remark}"></textarea> <li><input type="submit" value="Save Goods"> </ul> </form>
</body>
</html>
後面的是測試類的結果:
DateSourceTests.java
package com.cy.pj.common.datasource;
import java.sql.Connection;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class DataSourceTests {
/* * FAQ? * 請問dataSource對象在運行時指向的具體對象類型是什麼 兩種: * 一:對象。getclass()。getname();經過反射來找到指向的具體對象 二:經過debug測試來,將鼠標指向該鏈接就能夠看到具體對象 * 請問dataSource對象是有誰幫你建立的?spring框架(基於底層的基本配置)DataSourceAutoConfiguration */ @Autowired private DataSource datasource; //測試經過數據源DataSource對象獲取一個鏈接 @Test public void testConnection() throws Exception {
// //輸出datasource變量指向的對象的類型
// System.out.println(datasource.getClass().getName());//com.zaxxer.hikari.HikariDataSource
//請問獲取鏈接的過程你瞭解嗎 //第一次獲取鏈接時會檢測鏈接池是否存在,假如不存在則建立並初始化池 //基於Driver對象建立與數據庫的鏈接,並將鏈接放在池中 //最後從池中返回用戶的須要的鏈接 Connection conn = datasource.getConnection(); System.out.println(conn); }
}
GoodsDaoTests.java
package com.cy.pj.goods.dao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.cy.pj.goods.dao.GoodsDao;
@SpringBootTest
public class GoodsDaoTests {
/** 關聯數據層接口,並由spring爲其進行值的注入 * FAQ? * 1)GoodsDao指向的對象是誰,由誰建立?由誰管理 * 2)GoodsDao指向的內部對象會作什麼事情? 基於mybatis API進行會話操做 */ @Autowired private GoodsDao goodsdao; @Test void testDeleteId() { int rows = goodsdao.deleteById(1); System.out.println("rows=" + rows); } @Test void testDeleteObject() { int rows = goodsdao.deleteObjects(2,3); System.out.println("rows=" + rows); }
}
GoodsServiceTests.java
package com.cy.pj.goods.service;
import java.util.List;
/**
*/
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.cy.pj.goods.pojo.Goods;
@SpringBootTest
public class GoodsServiceTests {
@Autowired//has a private GoodsService goodsService; @Test void testFindGoods() { List<Goods> list = goodsService.findGoods(); for(Goods g:list) { System.out.println(g); } } @Test void testDeleteById() { int rows = goodsService.deleteById(10); System.out.println("rows=" +rows ); }
}
這一次的所須要的依賴注入,來自pom.xml文件中體現:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.cy</groupId> <artifactId>CGB-SBOOT-04</artifactId> <version>0.0.1-SNAPSHOT</version> <name>CGB-SBOOT-04</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!-- 此依賴提供了HikariCP鏈接池 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- 負責數據庫的的驅動程序 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <!-- 添加mybatis starter 依賴(SpringBoot 在這個依賴下提供mybatis的自動配置 --> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
</project>