1、首先点击 File---->New---->Project---->Spring Initializr---->next
2.填写项目信息–>next
intellij idea build时出现Artifact contains illegal characters的解决
3.勾选
Web=>Spring Web (或者Spring Web Starter);
SQL=> MySQL Driver,JDBC API 和 MyBatis Framework三项;
Developer Tools=>Lombok (未截图 同理选中)
Template Englines=>Thymeleaf;(未截图 同理选中)
然点击NEXT!
5 选择项目路径==>Finish
6.点击右侧的Maven,点击设置(扳手图标)进行项目Maven仓库的配置;
7.配置maven
8.如何没有自动导包,配置完可以点击左上角重新导包按钮,或者呢个下载按钮,选择下载所有源文件和文档
[.- 注意: 第八步骤结束 做其他项目的同学可以回到原先的博客了 !!]
9.在templates文件下新建demo.html页面,作为启动的初始页面;
10.创建controller包
11.创建一个demoController.class类
写一串跳转demo页面的代码
package com.wenjian.mywj.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class demoController {
@RequestMapping("/demo")
public String demo(){
return "demo";
}
}
12在resources中复制粘贴application.yml(或者新建都可以)(点击了解application.properties和application.yml的差异)
spring:
datasource:
name: demo #数据库名
url: jdbc:mysql://localhost:3306/demo #url链接
username: root #用户名
password: 123456 #密码
driver-class-name: com.mysql.jdbc.Driver #数据库链接驱动
14 打开浏览器(我这里是谷歌)
我们先将demo.html复制粘贴一个新的index.html
templates中localhost:8080默认跳转index.html(特性)
localhost:8080/demo调用controller中的/demo跳转
15 创建数据库demo
右键新建数据库
16右键demo数据库下面的表=>新建表user添加一条数据
如下:
16 创建架构entity包 dao包 service包 serviceImpl包 mapper包
17配置mybatis 并且在url后面添加?serverTimezone=Asia/Shanghai (不添加会报一个错误)
spring:
datasource:
name: demo #数据库名
url: jdbc:mysql://localhost:3306/demo?serverTimezone=Asia/Shanghai #url
username: root #用户名
password: 123456 #密码
driver-class-name: com.mysql.jdbc.Driver #数据库链接驱动
mybatis:
mapper-locations: classpath:mapper/*.xml #配置映射文件
type-aliases-package: com.wenjian.mywj.entity #配置实体类
18创建类
dao: UserMapper.java
entity: User.java
Service: UserService.java
ServiceImpl: UserServiceImpl.java
resources/mapper:UserMapper.xml.java
19代码如下:
(1)dao: UserMapper.java
package com.wenjian.mywj.dao;
import com.wenjian.mywj.entity.User;
import java.util.List;
public interface UserMapper {
List<User> getUserInfo();
}
(2)entity: User.java
package com.wenjian.mywj.entity;
import lombok.Data;
import java.util.Date;
/**
* 若是没有配置lombok可以生成get set
*/
@Data
public class User {
private Integer id;
private String name;
private String address;
private Date birth;
/* public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}*/
}
(3)Service: UserService.java
package com.wenjian.mywj.service;
import com.wenjian.mywj.dao.UserMapper;
import com.wenjian.mywj.entity.User;
import java.util.List;
public interface UserService {
List<User> getUserInfo();
}
(4)ServiceImpl: UserServiceImpl.java
package com.wenjian.mywj.serviceImpl;
import com.wenjian.mywj.dao.UserMapper;
import com.wenjian.mywj.entity.User;
import com.wenjian.mywj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired//讲Dao注入Service层
private UserMapper userMapper;
@Override
public List<User> getUserInfo() {
return userMapper.getUserInfo();
}
}
(5)resources/mapper: UserMapper.xml.java
<?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.wenjian.mywj.dao.UserMapper">
<select id="getUserInfo" resultType="com.wenjian.mywj.entity.User">
SELECT * FROM user
</select>
</mapper>
20 使用Test测试
(1)在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.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wenjian</groupId>
<artifactId>mywj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mywj</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--thymeleaf模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis配置-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!--mysql配置-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--lombok配置-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--单元测试配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
(2)给正式的启动MywjApplication中添加MapperScan扫描
package com.wenjian.mywj;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.wenjian.mywj.dao")//启动时扫描mapper接口,否则会报错找不到mapper文件
public class MywjApplication {
public static void main(String[] args) {
SpringApplication.run(MywjApplication.class, args);
}
}
(3)在test/java/com.wenjian.myw中测试
package com.wenjian.mywj;
import com.wenjian.mywj.dao.UserMapper;
import com.wenjian.mywj.entity.User;
import com.wenjian.mywj.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class MywjApplicationTests {
@Autowired
UserService userService;
@Test
public void contextLoads() {
List<User> userInfo = userService.getUserInfo();
//第一种遍历
for (User u: userInfo) {
System.out.println(u);
}
//第二种遍历
userInfo.forEach(u-> System.out.println(u));
}
}
运行结果:
--------------------------分割线-------------------------------------------------
做交互
(1) demoController添加getInfo方法
package com.wenjian.mywj.controller;
import com.wenjian.mywj.dao.UserMapper;
import com.wenjian.mywj.entity.User;
import com.wenjian.mywj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class demoController {
@Autowired
private UserService userService;
@RequestMapping("/demo")
public String demo(){
return "demo";
}
@ResponseBody
@RequestMapping(value = "/getInfo",method = RequestMethod.GET)
public List<User> getInfo(){
List<User> userInfo = userService.getUserInfo();
return userInfo;
}
}
(2) index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div id="ces" style="padding: 5px">
</div>
<script >
$.ajax({url:"/getInfo",success:function(result){
for (var item in result) {
console.log(item)
$("#ces").append('id:'
+result[item].id+'');
$("#ces").append('姓名:'
+result[item].name+'');
$("#ces").append('地址:'
+result[item].address+'');
$("#ces").append('生日:'
+result[item].birth+'
');
}
}});
</script>
</body>
</html>
由于每次改动html不自动刷新
点击链接可以增加热部署解决每次小改或者大改html需要重启项目的麻烦
https://blog.csdn.net/ws_dj_love/article/details/95445590
或者
https://www.cnblogs.com/erlongxizhu-03/p/12193646.html
pom.xml引入
com.baomidou
mybatis-plus-boot-starter
3.2.0
org.springframework.boot
spring-boot-starter-freemarker
com.baomidou
mybatis-plus-generator
3.2.0
完整的
4.0.0
com.hailan
hailan
0.0.1-SNAPSHOT
hailan
Demo project for Spring Boot
1.8
UTF-8
UTF-8
2.3.7.RELEASE
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.4
com.baomidou
mybatis-plus-boot-starter
3.2.0
org.springframework.boot
spring-boot-starter-freemarker
com.baomidou
mybatis-plus-generator
3.2.0
org.springframework.boot
spring-boot-devtools
runtime
true
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-dependencies
${spring-boot.version}
pom
import
org.apache.maven.plugins
maven-compiler-plugin
3.8.1
1.8
UTF-8
org.springframework.boot
spring-boot-maven-plugin
2.3.7.RELEASE
com.hailan.hailan.HailanApplication
repackage
repackage
新建CodeGenerator类
修改成自己的数据库和对应的包就可以直接运行了生成了
package com.ceshi;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
//URL地址
private final static String URL="jdbc:mysql://localhost:3306/tongbu?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC";
//数据库账号
private final static String USERNAME= "root";
//数据库密码
private final static String PASSWORD= "123456";
//安装位置 包的路径
private final static String PARENT="com.tongbu";
//数据库驱动
private final static String DRIVERNAME ="com.mysql.cj.jdbc.Driver";
// 如果模板引擎是 freemarker
private final static String TEMPLATEPATH = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
/**
*
* 读取控制台内容
*
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
// gc.setOutputDir("D:\\test");
gc.setAuthor("深林中的书海");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc);
// 数据源配置 数据库名 账号密码
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(URL);
// dsc.setSchemaName("public");
dsc.setDriverName(DRIVERNAME);
dsc.setUsername(USERNAME);
dsc.setPassword(PASSWORD);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(null);
pc.setParent(PARENT);
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = TEMPLATEPATH;
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!
return projectPath + "/src/main/resources/mapper/"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix("m_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
借鉴application.yml:
# DataSource Config
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/hailan?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
username: root
password: 123456
resources:
static-locations: classpath:/static/
#模版配置
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
#模版模式
mode: HTML5
encoding: UTF-8
servlet:
content-type: text/html
multipart:
max-file-size: 1024MB
max-request-size: 1024MB
# 热部署
devtools:
restart:
# 是否启用重启
enabled: true
# 设置重启的目录
additional-paths: src/main/java
#classpath目录下的WEB-INF文件夹内容修改不重启
spring.devtools.restart.exclude: WEB-INF/**
# 指定程序的配置文件
# profiles: dev
mybatis-plus:
mapper-locations: classpath*:/mapper/**Mapper.xml
server:
port: 8080
shiro-reids:
enabled: true
redis-manager:
host: 127.0.0.1:6379
借鉴pom.xml(我这里引入了代码生成器)
4.0.0
com.hailan
hailan
0.0.1-SNAPSHOT
hailan
Demo project for Spring Boot
1.8
UTF-8
UTF-8
2.3.7.RELEASE
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.4
com.baomidou
mybatis-plus-boot-starter
3.2.0
org.springframework.boot
spring-boot-starter-freemarker
com.baomidou
mybatis-plus-generator
3.2.0
org.springframework.boot
spring-boot-devtools
runtime
true
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-dependencies
${spring-boot.version}
pom
import
org.apache.maven.plugins
maven-compiler-plugin
3.8.1
1.8
UTF-8
org.springframework.boot
spring-boot-maven-plugin
2.3.7.RELEASE
com.hailan.hailan.HailanApplication
repackage
repackage