这里写自定义目录标题
- 第一次使用springboot
- 1、搭建一个springboot的项目
- 2、update springboot default resources path (修改springboot默认资源路径)
- 3、Integrated thymeleaf engine template (集成thymeleaf引擎模板)
- 3、integration lombok (集成lombok)
- 4、引入jackson进行对象与json互相转换
- 5、将配置文件中的key value 映射为一个JavaBean
- 5、使用okhttp发送网络请求
- 6、配置Hikari数据源(springboot自带),以及连接h2数据库
- 7、集成mybatis
- 8、配置通用mapper (xk.mybatis)
- 9、配置数据库迁移插件flyway
- 10、通过spring-boot-starter-data-jpa 进行通过javaBean自动建表()
- 11、使用pageHelper分页功能
第一次使用springboot
1、搭建一个springboot的项目
- create one idea Project (创建一个项目)
- next select all default (一路next)
2、update springboot default resources path (修改springboot默认资源路径)
- find the springboot.application file under the resources path (在类路径下找到springboot.applicatsion文件)
- 添加spring.resources.static-locations配置
# Multiple paths are separated by commas instead of double quotes(多个路径之间用逗号隔开,不用加双引号)
spring.resources.static-locations=
classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/config/
3、Integrated thymeleaf engine template (集成thymeleaf引擎模板)
- at pom.xml add dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- configuration applicationi.properties
#thymeleaf engine template configuration,reference org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties类
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
# prefix and suffix (前缀和后缀的配置,要配置资源目录下所在路径,默认前缀为/template/,后缀为.html)
spring.thymeleaf.prefix=
spring.thymeleaf.suffix=
# close cache 开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
- thymeleaf base grammar 基础语法
<!-- head,prevent show error -->
<html xmlns:th="http://www.thymeleaf.org">
<!-- The introduction of resources 引入其他资源,图片,css,js等等-->
<script th:src='@{/js/jquery.js}'></script>
<script th:src='@{/js/utils.js}'></script>
<script th:src='@{/layui/layui.js}'></script>
<script th:src='@{/js/template.min.js}'></script>
<link rel='stylesheet' th:href='@{layui/layui.css}' type='text/css'>
<link rel='stylesheet' th:href='@{normalize/base.css}' type='text/css'>
<link rel='stylesheet' th:href='@{normalize/normalize.css}' type='text/css'>
<!-- The include or replace of other html 引入或者替换其他html-->
<div th:include="common/header"></div>
<div th:replace="common/header"></div>
<!-- get session data 获取session数据-->
<div th:text="${session.data}" />
<!-- Ternary operator 三目运算符 -->
<div th:text="${data.isShow==null?1:0}" />
<!-- foreach | loop data 循环 -->
<li th:each="item,stat:${ data.persons }">
<img th:src="${ item.user.logo }" alt="">
</li>
3、integration lombok (集成lombok)
- add dependency
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
- add annotation at JavaBean
// get and set
@Data
//全参构造函数
@AllArgsConstructor
//空参构造函数
@NoArgsConstructor
public class Result {
private int code;
private String msg;
}
4、引入jackson进行对象与json互相转换
- 添加pom.xml中的依赖
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.3</version>
</dependency>
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.3</version>
</dependency>
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.3</version>
</dependency>
- 创建一个jsonUtils
@Component //这个可以不加,我加了是为了@Autowried 直接拿而已。其实可以直接JsonUtils.方法名(参数)调用
public class JsonUtils {
/*
* json转对象
* @param:传入需要被返回的对象 and 需要被转换的json字符
* @return:Object
*/
public static Object jsonToObj(Object obj,String jsonStr) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(jsonStr, obj.getClass());
}
/*
* 对象转json
* @param:传入需要转换为json字符串的对象
* @return:json字符串
*/
public static String objToJson(Object obj) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(obj);
}
}
- 调用的时候,如果对象中的属性与json中的key 属性不一致,会出现字段为空的情况。解决方法:
@JsonProperty(value = "avatar_url")
private String logo;
- 当bean对象的属性与json数据的key不完全匹配时,可以忽略掉其他属性
@JsonIgnoreProperties(ignoreUnknown = true) //作用于类上
5、将配置文件中的key value 映射为一个JavaBean
如果名称一样的话可以不用 @Value("${client_id}")
@Component
@PropertySource(value = "classpath:config/github.properties")
@ConfigurationProperties(prefix = "github")
@Data
public class GitHubProperties {
private String client_id;
private String client_secret;
private String post_url;
private String redirect_url;
private String code;
}
如果报错的话添加依赖
<!-- 解决@ConfigurationProperties报错问题-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
5、使用okhttp发送网络请求
- 引入依赖
<!-- OKhttp网络请求 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.4.1</version>
</dependency>
- 创建工具类
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class HttpUtils {
public static final MediaType JSON
= MediaType.get("application/json; charset=utf-8");
//封装一个普通的get方法,返回一个字符串
public static String get(String url) throws IOException {
OkHttpClient client = getClient();
Request request = new Request.Builder()
.url(url).build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
//通过object对象进行post请求,会将object对象转换为json数据提交
public static String post(String url,Object obj) throws IOException {
OkHttpClient client = getClient();
RequestBody body = RequestBody.create(JsonUtils.objToJson(obj), JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
private static OkHttpClient getClient(){
return new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)//设置连接超时时间
.readTimeout(20, TimeUnit.SECONDS)//设置读取超时时间
.build();
}
}
6、配置Hikari数据源(springboot自带),以及连接h2数据库
- 引入依赖
<!-- h2数据库-->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- 这样即可使用spingboot默认自带的HikariCP数据源-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
- 配置连接池
spring.datasource.hikari.jdbc-url=jdbc:h2:D:/studySpringBoot/communitybbs/src/main/java/top/itxcb/communitybbs
spring.datasource.hikari.driver-class-name=org.h2.Driver
spring.datasource.hikari.username=root
spring.datasource.hikari.password=root
- 先使用idea的DateBase连接工具进行连接
- 连接的地址就写当前项目的地址
- 然后打开h2数据库的控制台,重置一下用户名密码
create user if not exists 用户名 password “密码”;
alter user 用户名 admin true;
7、集成mybatis
- 添加依赖
<!-- mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
- 配置application.properties
#配置mybatis
#配置别名
mybatis.type-aliases-package=top.itxcb.communitybbs.bean
#配置mapper.xml映射文件所在位置
mybatis.mapper-locations=classpath:mapperimpl/*.xml
#配置bean对象的驼峰标识与数据库中的_分割的数据映射一致
mybatis.configuration.map-underscore-to-camel-case=true
- 在启动类中扫描dao
@MapperScan(basePackages = "com.mapper.*")
8、配置通用mapper (xk.mybatis)
- 添加依赖
<!-- 通用mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${tk.mybatis.version}</version>
</dependency>
- 配置application.properties
#配置通用mapper,这个mapper不会能被上面那个@扫描到,不然会报错
mapper.mappers=top.itxcb.communitybbs.common.mapper.BaseMapper
#定义数据库
#mapper.identity=H2
mapper.identity=MYSQL
- 在启动类中添加注解扫描dao,注意:这个注解要用xk的。不能用mybatis自带的
import tk.mybatis.spring.annotation.MapperScan;
@MapperScan("top.itxcb.communitybbs.mapper")
9、配置数据库迁移插件flyway
- 在pom.xml文件中添加插件
<!-- 数据库迁移插件flyway -->
<plugin>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>6.3.1</version>
<configuration>
<url>jdbc:h2:D:/studySpringBoot/communitybbs/src/main/java/top/itxcb/communitybbs</url>
<user>root</user>
<password>root</password>
</configuration>
<!--这里写你要连接的数据库-->
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
</dependencies>
</plugin>
- 在resources目录下创建db文件夹以及migration子文件夹,在里面存放对应需要执行的sql,
注意开头的版本与 2个下划线
- 然后可以在终端执行mvn flyway:migrate,就可以了
10、通过spring-boot-starter-data-jpa 进行通过javaBean自动建表()
- 加依赖
<!-- Spring-data-jpa依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
- 在配置文件中添加
#配置自动建表:updata:没有表新建,有表更新操作,控制台显示建表语句
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
- 需要建表的JavaBean配置
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
@Data
@Table(name="user")
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id//主键字段
//@GeneratedValue注解存在的意义主要就是为一个实体生成一个唯一标识的主键、@GeneratedValue提供了主键的生成策略。
@GeneratedValue(strategy=GenerationType.IDENTITY,generator="Mysql")
private Integer id;
@Column(name="access_id")
private String accessId;
private String name;
private String token;
//头像地址
private String logo;
//对应数据库中的字段,如果数据库中的字段是关键字(保留字)
// 则可以添加Tab按键上的那个点: @Column(name="`gmt_create`")
@Column(name="gmt_create")
private Long gmtCreate;
@Column(name = "gmt_modified")
private Long gmtModified;
@Transient //表示这个字段不是数据库中的字段
private String testConlum;
11、使用pageHelper分页功能
- 添加依赖
<!-- mybatis分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper.version}</version>
</dependency>
- 添加配置
#pagehelper配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
- 创建pageBean分页对象
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
public class PageBean<T> {
// 当前页
private Integer currentPage = 1;
// 每页显示的总条数
private Integer pageSize = 10;
// 总条数
private Integer totalNum;
// 是否有下一页
private Integer isMore;
// 总页数
private Integer totalPage;
// 开始索引
private Integer startIndex;
// 分页结果
private List<T> lists;
public PageBean(Integer currentPage, Integer pageSize, Integer totalNum) {
super();
this.currentPage = currentPage;
this.pageSize = pageSize;
this.totalNum = totalNum;
this.totalPage = (this.totalNum + this.pageSize - 1) / this.pageSize;
this.startIndex = (this.currentPage - 1) * this.pageSize;
this.isMore = this.currentPage >= this.totalPage ? 0 : 1;
}
}
- 在代码中使用 ,只需要在查询方法前调用PageHelper.startPage方法即可
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.autoconfigure.PageHelperProperties;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.itxcb.communitybbs.bean.Publish;
import top.itxcb.communitybbs.bean.PublishDTO;
import top.itxcb.communitybbs.bean.User;
import top.itxcb.communitybbs.common.utils.PageBean;
import top.itxcb.communitybbs.mapper.PublishMapper;
import top.itxcb.communitybbs.mapper.UserMapper;
import java.util.ArrayList;
import java.util.List;
@Service
public class PublishService {
@Autowired
PublishMapper publishMapper;
@Autowired
private UserMapper userMapper;
public PageBean<PublishDTO> findAll(Integer pageNum, Integer pageSize) {
List<PublishDTO> publishList = new ArrayList<>();
PageHelper.startPage(pageNum, pageSize);
List<Publish> publishs = publishMapper.selectAll();
int numCount = publishMapper.selectCount(null);
for (Publish publish : publishs) {
PublishDTO publishDTO = new PublishDTO();
User user = userMapper.selectByPrimaryKey(publish.getUserId());
BeanUtils.copyProperties(publish,publishDTO);
publishDTO.setUser(user);
publishList.add(publishDTO);
}
PageBean<PublishDTO> pageBean = new PageBean<>(pageNum,pageSize,numCount);
pageBean.setLists(publishList);
return pageBean;
}
}
本篇博客为简单做个学习笔记
如果有涉及到任何侵权,请联系我