1、Springboot
1.1觉壶、Idea 從頭搭建Springboot+Maven的web項目
1.創(chuàng)建新項目
打開編輯器,F(xiàn)ile-->New-->project,
2.配置環(huán)境變量
然后選擇Spring Initializr件缸,配置包的名稱铜靶,路徑等
3.添加依賴
選擇依賴,這里我們添加Spring Web他炊,Mybatis Framework,MySQLDriver這幾個就可以争剿,添加成功后可以在右側(cè)看到
4.項目目錄結(jié)構(gòu)
點(diǎn)擊Finish項目創(chuàng)建完畢,目錄結(jié)構(gòu)如下所示:
5.配置application.yml
首先將application.properties重命名為.yml文件痊末,然后配置端口蚕苇、數(shù)據(jù)庫、和mybatis
server:
port:8080
spring:
devtools:
restart:
enabled:false
? ? livereload:
enabled:true
? datasource:
url: jdbc:mysql://localhost:3306/edison?serverTimezone=Asia/Shanghai&characterEncoding=utf-8
username: root
password: 4568
driver-class-name:com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapping/*.xml
type-aliases-package: com.example.model
#showSql
logging:
level:
com:
example:
mapper :debug
6.web界面測試
在static目錄下創(chuàng)建index.html,隨便寫點(diǎn)測試內(nèi)容舌胶,然后點(diǎn)擊右上角的啟動按鈕
項目啟動完成之后捆蜀,打凱瀏覽器,輸入“l(fā)ocalhost:8080”,即可訪問剛才寫的測試頁面
7.整合mybatis
a.使用generatoConfig.xml的配置完成逆向工程配置
首先在pom.xml中添加相關(guān)依賴和插件
<?xmlversion="1.0" encoding="UTF-8"?>
<projectxmlns="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.6.4</version>
<relativePath/><!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springbootDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootDemo</name>
<description>springbootDemo</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- generator自動生成代碼依賴包 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!--generator插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<!--指定mybatis? core 可省略-->
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency>
</dependencies>
<!--導(dǎo)入之后執(zhí)行-->
<executions>
<execution>
<id>mybatis-generattor</id>
<!--phase階段-->
<phase>package</phase>
<!--目的-->
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<!--插件配置-->
<configuration>
<!--是否允許移動生成的文件-->
<verbose>true</verbose>
<!--是否循序自動覆蓋幔嫂,測試環(huán)境為true 非測試false-->
<overwrite>true</overwrite>
<!--mybatis配置文件路徑-->
<configurationFile>
? ? ? ? ? ? ? ? ? ? ?? src/main/resources/mybatis/generatorConfig.xml
</configurationFile>
</configuration>
</plugin>
</plugins>
</build>
</project>
然后在src/main/resources/mybatis下創(chuàng)建generatorConfig.xml,目錄路徑與pom.xml中的路徑保持一致誊薄。具體配置信息如下:(注意生成文件的存放路徑需要與項目的實際路徑保持一致)履恩。
<?xmlversion="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>
<!-- 數(shù)據(jù)庫驅(qū)動:選擇你的本地硬盤上面的數(shù)據(jù)庫驅(qū)動包-->
<classPathEntrylocation="D:\MvnLocal2\mysql\mysql-connector-java\8.0.13\mysql-connector-java-8.0.13.jar"/>
<contextid="mysql"targetRuntime="MyBatis3">
<commentGenerator>
<propertyname="suppressDate"value="true"/>
<!-- 是否去除自動生成的注釋 true:是 : false:否 -->
<propertyname="suppressAllComments"value="true"/>
</commentGenerator>
<!--數(shù)據(jù)庫鏈接URL,用戶名呢蔫、密碼 -->
<jdbcConnectiondriverClass="com.mysql.cj.jdbc.Driver"connectionURL="jdbc:mysql://127.0.0.1:3306/edison?&useSSL=false&useUnicode=true&characterEncoding=utf-8&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai"
userId="root"password="4568">
</jdbcConnection>
<javaTypeResolver>
<propertyname="forceBigDecimals"value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGeneratortargetPackage="com.example.springbootDemo.model"targetProject="src/main/java">
<propertyname="enableSubPackages"value="true"/>
<propertyname="trimStrings"value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGeneratortargetPackage="mapping"targetProject="src/main/resources">
<propertyname="enableSubPackages"value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGeneratortype="XMLMAPPER"targetPackage="com.example.springbootDemo.dao"targetProject="src/main/java">
<propertyname="enableSubPackages"value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是數(shù)據(jù)庫中的表名或視圖名 domainObjectName是實體類名-->
<tableschema=""tableName="userinfo"domainObjectName="UserInfo"enableCountByExample="true"
enableUpdateByExample="true"enableDeleteByExample="true"enableSelectByExample="true"
selectByExampleQueryId="true">
</table>
</context>
</generatorConfiguration>
配置完成后切心,Reload項目飒筑,然后點(diǎn)擊maven下的mybatis-generator插件
運(yùn)行結(jié)束后,dao绽昏、mapper协屡、model自動創(chuàng)建完成,之后目錄結(jié)構(gòu)如下:
8.web查詢demo
接下來我們可以通過簡單的demo來實現(xiàn)前后臺交互完成查詢全谤。
a.controller層
packagecom.example.controller;
importcom.alibaba.fastjson.JSONObject;
importcom.example.service.UserInfoService;
importcom.example.model.UserInfo;
importcom.example.model.UserInfoExample;
importcom.example.util.PbConstants;
importcom.sun.deploy.net.HttpResponse;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.bind.annotation.RestController;
importorg.springframework.web.servlet.ModelAndView;
importjavax.servlet.http.HttpServletRequest;
importjava.util.ArrayList;
importjava.util.List;
@RestController
@RequestMapping("/user")
publicclassUserInfoController{
@Autowired
privateUserInfoServiceuserInfoService;
/**
* 登錄
* @return
*/
@RequestMapping(value="/login",method=RequestMethod.POST)
publicList<UserInfo>loginByusername(Stringusername,Stringpassword){
// ? ? ?? username = "edison";
// ? ? ?? password = "111";
returnuserInfoService.getUserInfo(username,password);
?? }
/**
* 獲取所有用戶
* @return
*/
@RequestMapping(value="/getAllUserInfo",method=RequestMethod.GET)
publicList<UserInfo>getAllUserInfo(){
returnuserInfoService.getAllUserInfo();
?? }
}
b.service層
packagecom.example.service;
importcom.alibaba.fastjson.JSONObject;
importcom.example.mapper.UserInfoMapper;
importcom.example.model.UserInfo;
importcom.example.model.UserInfoExample;
importcom.example.util.PbConstants;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Service;
importorg.springframework.web.servlet.ModelAndView;
importjava.util.ArrayList;
importjava.util.List;
@Service
publicclassUserInfoService{
@Autowired
privateUserInfoMapperuserInfoMapper;
publicList<UserInfo>getUserInfo(Stringusername,Stringpassword){
List<UserInfo>list=userInfoMapper.getUserInfo(username,password);
returnlist;
? ? ?? }
publicList<UserInfo>getAllUserInfo(){
List<UserInfo>userInfos=newArrayList<>();
userInfos=userInfoMapper.getAllUserInfo();
returnuserInfos;
? ? ?? }
}
c.由于model和mapper是自動生成的肤晓,因為我另外新加了一個查詢所以表記錄的方法,因此這里只展示mapper代碼:
packagecom.example.mapper;
importcom.example.model.UserInfo;
importcom.example.model.UserInfoExample;
importjava.util.List;
importorg.apache.ibatis.annotations.*;
@Mapper
publicinterfaceUserInfoMapper{
longcountByExample(UserInfoExampleexample);
intdeleteByExample(UserInfoExampleexample);
@Delete({
"delete from userinfo",
"where id = #{id,jdbcType=VARCHAR}"
?? })
intdeleteByPrimaryKey(Stringid);
@Insert({
"insert into userinfo (id, username, ",
"password, yxbz, ",
"by1, by2, by3, ",
"by4)",
"values (#{id,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, ",
"#{password,jdbcType=VARCHAR}, #{yxbz,jdbcType=VARCHAR}, ",
"#{by1,jdbcType=VARCHAR}, #{by2,jdbcType=VARCHAR}, #{by3,jdbcType=VARCHAR}, ",
"#{by4,jdbcType=VARCHAR})"
?? })
intinsert(UserInforecord);
intinsertSelective(UserInforecord);
List<UserInfo>selectByExample(UserInfoExampleexample);
@Select({
"select",
"id, username, password, yxbz, by1, by2, by3, by4",
"from userinfo",
"where id = #{id,jdbcType=VARCHAR}"
?? })
@ResultMap("com.example.mapper.UserInfoMapper.BaseResultMap")
UserInfoselectByPrimaryKey(Stringid);
@Select({
"select",
"id, username, password, yxbz, by1, by2, by3, by4",
"from userinfo",
"where username = #{username,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR} "
?? })
@ResultMap("com.example.mapper.UserInfoMapper.BaseResultMap")
List<UserInfo>getUserInfo(Stringusername,Stringpassword);
@Select({
"select",
"id, username, password, yxbz, by1, by2, by3, by4",
"from userinfo"
?? })
@ResultMap("com.example.mapper.UserInfoMapper.BaseResultMap")
List<UserInfo>getAllUserInfo();
intupdateByExampleSelective(@Param("record")UserInforecord,@Param("example")UserInfoExampleexample);
intupdateByExample(@Param("record")UserInforecord,@Param("example")UserInfoExampleexample);
intupdateByPrimaryKeySelective(UserInforecord);
@Update({
"update userinfo",
"set username = #{username,jdbcType=VARCHAR},",
"password = #{password,jdbcType=VARCHAR},",
"yxbz = #{yxbz,jdbcType=VARCHAR},",
"by1 = #{by1,jdbcType=VARCHAR},",
"by2 = #{by2,jdbcType=VARCHAR},",
"by3 = #{by3,jdbcType=VARCHAR},",
"by4 = #{by4,jdbcType=VARCHAR}",
"where id = #{id,jdbcType=VARCHAR}"
?? })
intupdateByPrimaryKey(UserInforecord);
}
d.測試頁面index.html
<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>springbootDemo</title>
<style>
? ? ?? *{
margin:0;
padding:0;
? ? ?? }
.result{
position:fixed;
width:100%;
bottom:0;
left:0;
height:600px;
background-color:rgba(0,0,0,.8);
color:white;
text-align:center;
letter-spacing:2px;
padding-top:20px;
font-size:18px;
line-height:28px;
overflow:scroll;
? ? ?? }
</style>
</head>
<body>
<scriptsrc="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<buttonstyle="display: block;margin: 20px auto;width: 160px;height: 60px;"onclick="getAll()">查看所有用戶信息</button>
<divclass="result"id="result"></div>
<script>
functiongetAll(){
$.ajax({
type:"get",
url:"user/getAllUserInfo",
data: {
? ? ? ? ?? },
success:function(data) {
console.log(data)
$("#result").empty()
for(vari=0;i<data.length;i++){
$("#result").append(JSON.stringify(data[i])+"<br>")
? ? ? ? ? ? ?? }
? ? ? ? ?? },
? ? ?? });
?? }
</script>
</body>
</html>
e.結(jié)果展示
點(diǎn)擊運(yùn)行項目认然,瀏覽輸入localhost:8080,點(diǎn)擊查詢所有用戶信息
至此补憾,一個簡單的springboot+maven的web項目demo就完成了。