Spring boot 实战
搭建第一个spring-boot项目
- 访问 https://start.spring.io/ , 选择好之后, 点击 generate, 会生成对应的压缩包。
- idea 导入对应的文件, 设置 maven仓库和jdk(1.8)
- resources目录下添加 banner.txt,
banner生成网站: http://patorjk.com/software/taag/
- 配置application.properties文件
# 端口
server.port=8080
# 文根
server.servlet.context-path=/itboat008
- 配置 Controller:
package com.itboat008.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller// (value="/user") 这里做配置请求对应url会报404
@RequestMapping(value="/user")
public class UserController {
@RequestMapping("getUser")
@ResponseBody
public String getUser(){return "itboat008";}
}
- 启动类
package com.itboat008.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
项目结构:
- 启动项目后, 访问 : http://localhost:8080/itboat008/user/getUser
使用 RestController
package com.itboat008.springboot.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController// (value="/order") 这里做配置请求对应url会报404
@RequestMapping("/order")
public class OrderController {
@GetMapping("/getOrder")
public String getOrder(){return "asd";}
}
注意:
@RestController 和 @Controller 配置 value属性不会作用到 请求路径中去, 需采用 @RequestMapping里面的
属性去拼接请求url。
使用thymeleaf动态模板
引用pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Controller 中配置页面动态传参
package com.itboat008.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
@Controller// (value="/user") 这里做配置请求对应url会报404
@RequestMapping(value="/user")
public class UserController {
@RequestMapping("sayHello")
public String sayHello(Map<String,String> params){
String hello = "hello , my name is itboat008";
params.put("hello",hello);
return "User";
}
}
classpath下的templates中添加User.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span style="color:red" th:text="${hello}"></span>
</body>
</html>
application.properties中添加thymeleaf配置
server.port=8080
server.servlet.context-path=/itboat008
#thymelea模板配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
#HTML5已经弃用
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
#页面不缓存
spring.thymeleaf.cache=false
注意:
因为spring.thymeleaf.prefix配置的是classpath路径下, 修改html或者添加html需要重启或者maven重新clean install,才能生效。
springboot 整合 h2 + MyBatis
注意:
当maven打包出现failure时候, 需要看具体的异常:
#maven 打包命令, 打印异常堆栈, 忽略测试用例
mvn clean install -e -X -DskipTests
报错内容:
org.apache.maven.plugin.MojoExecutionException: Input length = 1
原因是缺失 maven插件, 在pom.xml中添加 如下配置,重新clean install之后,问题解决
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-filtering</artifactId>
<version>1.3</version>
</dependency>
</dependencies>
</plugin>
maven 中添加依赖:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.4</version>
</dependency>
application.properties中添加配置
#####################mybatis###########################
mybatis.mapper-locations=classpath:mappings/*Mapper.xml
mybatis.type-aliases-package=com.itboat008.springboot.entity
################h2#################################
#DDL
spring.sql.init.schema-locations=classpath:db/schema.sql
#DML
spring.sql.init.data-locations= classpath:db/data.sql
#开通远程访问
spring.h2.console.settings.web-allow-others=true
#控制台地址
spring.h2.console.path=/h2
spring.h2.console.enabled=true
spring.h2.console.settings.trace=true
spring.datasource.url=jdbc:h2:mem:itboat008
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=itboat008
spring.datasource.password=123456
在classpath:db路径下创建schema.sql文件
create table fnd_user_t(
id integer primary key ,
user_name varchar(100),
user_code varchar(100),
company_id integer
);
create table fnd_company_t(
id integer primary key ,
company_name varchar(100),
company_code varchar(100)
);
在classpath:db路径下创建data.sql文件
insert into fnd_user_t(id ,user_name,user_code ,company_id )values (1,'张三丰','zhangsanfeng',1);
insert into fnd_user_t(id ,user_name,user_code ,company_id )values (2,'赵敏','zhaomin',1);
insert into fnd_user_t(id ,user_name,user_code ,company_id )values (3,'令狐冲','linghuchong',1);
insert into fnd_user_t(id ,user_name,user_code ,company_id )values (4,'田伯光','tianboguang',2);
insert into fnd_user_t(id ,user_name,user_code ,company_id )values (5,'欧阳锋','ouyangfeng',2);
insert into fnd_user_t(id ,user_name,user_code ,company_id )values (6,'一灯','yideng',3);
commit ;
insert into fnd_company_t(id ,company_name ,company_code )values (1,'广西','guangxi');
insert into fnd_company_t(id ,company_name ,company_code )values (2,'江苏','jiangsu');
insert into fnd_company_t(id ,company_name ,company_code )values (3,'青海','qinghai');
commit;
浏览器访问h2控制台
访问: http://localhost:8080/itboat008/h2
可以看到数据已经有了。
application.properties添加配置:
#####################mybatis###########################
mybatis.mapper-locations=classpath:mappings/*Mapper.xml
mybatis.type-aliases-package=com.itboat008.springboot.entity
# 打印sql语句
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 驼峰命名法
mybatis.configuration.map-underscore-to-camel-case=true
########## 分页插件 ##########
pagehelper.helper-dialect=h2
pagehelper.params-count=countSql
pagehelper.reasonable=false
pagehelper.support-methods-arguments=true
################h2#################################
#DDL
spring.sql.init.schema-locations=classpath:db/schema.sql
#DML
spring.sql.init.data-locations= classpath:db/data.sql
#开通远程访问
spring.h2.console.settings.web-allow-others=true
#控制台地址
spring.h2.console.path=/h2
spring.h2.console.enabled=true
spring.h2.console.settings.trace=true
spring.datasource.url=jdbc:h2:mem:itboat008
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=itboat008
spring.datasource.password=123456
用MyBatis连接操作数据库
问题1:
当出现如下报错时候:
java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
因为 mybatis-spring-boot-starter 的版本不对, 设置版本,重启,问题解决:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
原因: Mybatis3依赖的jar包"mybatis-spring-1.2.0.jar"这个版本以及以上的版本中,对SqlSessionDaoSupport类中的’sqlSessionFactory’或’sqlSessionTemplate’注入方式进行了调整
问题2:
出现Invalid bound statement (not found): 原因 : *Mapper.xml文件和Mapper接口未能匹配, 注意排查:
- Mapper文件中的 namespace 和实际的Mapper路径是否一致
- 排查 target/classes下 是否可以找到对应的 *Mapper.xml 文件
- 排查 application.properties文件中配置的 mybatis.mapper-locations 和 mybatis.type-aliases-package 是否正确
问题3:
数据库字段带下划线的,查出字段为null, 解决: application.properties文件添加配置:
# 驼峰命名法
mybatis.configuration.map-underscore-to-camel-case=true
项目结构:
UserMapper.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.itboat008.springboot.repository.UserMapper">
<resultMap id="BaseResultMap" type="com.itboat008.springboot.entity.User">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="userName" jdbcType="VARCHAR" property="userName" />
<result column="userCode" jdbcType="VARCHAR" property="userCode" />
<result column="companyId" jdbcType="INTEGER" property="companyId" />
</resultMap>
<select id="findById" resultType="com.itboat008.springboot.entity.User">
select * from fnd_user_t where id = #{id}
</select>
<select id="findUsersByCompanyId" resultType="com.itboat008.springboot.entity.User">
select * from fnd_user_t where company_id = #{companyId}
</select>
<select id="findUsers" resultType="com.itboat008.springboot.entity.User">
select * from fnd_user_t
</select>
<delete id="deleteById" parameterType="int">
delete from fnd_user_t x where x.id = #{id}
</delete>
<insert id="addUser" parameterType="com.itboat008.springboot.entity.User">
insert into fnd_user_t
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="userName != null" >
user_name,
</if>
<if test="userCode != null" >
user_code,
</if>
<if test="companyId != null" >
company_id,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null" >
#{userName,jdbcType=VARCHAR},
</if>
<if test="userCode != null" >
#{userCode,jdbcType=VARCHAR},
</if>
<if test="companyId != null" >
#{companyId,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateUser" parameterType="com.itboat008.springboot.entity.User">
update fnd_user_t
<set >
<if test="userName != null" >
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="userCode != null" >
user_code = #{userCode,jdbcType=VARCHAR},
</if>
<if test="companyId != null" >
company_id = #{companyId,jdbcType=INTEGER},
</if>
</set>
where id = #{id}
</update>
</mapper>
源码:
PageHelperConfig:
package com.itboat008.springboot.config;
import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class PageHelperConfig {
@Bean
public PageHelper pageHelper() {
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("offsetAsPageNum", "true");
properties.setProperty("rowBoundsWithCount", "true");
properties.setProperty("reasonable", "false");
properties.setProperty("dialect", "h2");
pageHelper.setProperties(properties);
return pageHelper;
}
}
OrderController:
package com.itboat008.springboot.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController// (value="/order") 这里做配置请求对应url会报404
@RequestMapping("/order")
public class OrderController {
@GetMapping("/getOrder")
public String getOrder(){return "asd";}
}
UserController:
package com.itboat008.springboot.controller;
import com.itboat008.springboot.entity.ResultVO;
import com.itboat008.springboot.entity.User;
import com.itboat008.springboot.service.UserService;
import com.itboat008.springboot.utils.PageRequest;
import com.itboat008.springboot.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.Map;
@Controller// (value="/user") 这里做配置请求对应url会报404
@RequestMapping(value="/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("getUser")
@ResponseBody
public String getUser(){return "itboat008";}
@RequestMapping("sayHello")
public String sayHello(Map<String,String> params){
String hello = "hello , my name is itboat008";
params.put("hello",hello);
return "User";
}
@GetMapping("findById")
@ResponseBody
public User findById(@RequestParam(value="id") Integer id){
return userService.findById(id);
}
@GetMapping("/findUsersByCompanyId/{companyId}")
@ResponseBody
public List<User> findUsersByCompanyId(@PathVariable Integer companyId){
return userService.findUsersByCompanyId(companyId);
}
@GetMapping("/findUserByPage")
@ResponseBody
public PageResult findUserByPage(@RequestBody PageRequest pageRequest){
return userService.findUserByPage(pageRequest);
}
@PostMapping("/deleteById")
@ResponseBody
public ResultVO deleteById(@RequestParam("id") Integer id){
ResultVO resultVO = new ResultVO();
userService.deleteById(id);
resultVO.setResFlag("1");
resultVO.setResInfo("success");
return resultVO;
}
@PostMapping("/addUser")
@ResponseBody
public ResultVO addUser(@RequestBody User user){
ResultVO resultVO = new ResultVO();
userService.addUser(user);
resultVO.setResFlag("1");
resultVO.setResInfo("success");
return resultVO;
}
@PostMapping("/updateUser")
@ResponseBody
public ResultVO updateUser(@RequestBody User user){
ResultVO resultVO = new ResultVO();
userService.updateUser(user);
resultVO.setResFlag("1");
resultVO.setResInfo("success");
return resultVO;
}
}
ResultVO:
package com.itboat008.springboot.entity;
import lombok.Data;
@Data
public class ResultVO {
private String resFlag;
private String resInfo;
}
User:
package com.itboat008.springboot.entity;
import lombok.Data;
@Data
public class User {
private Integer id;
private String userName;
private String userCode;
private Integer companyId;
}
UserMapper:
package com.itboat008.springboot.repository;
import com.itboat008.springboot.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Mapper
public interface UserMapper {
User findById(int id);
List<User> findUsersByCompanyId(Map<String,Object> params);
List<User> findUsers();
void deleteById(Map<String,Integer> params);
void addUser(User user);
void updateUser(User user);
}
UserService:
package com.itboat008.springboot.service;
import com.itboat008.springboot.entity.ResultVO;
import com.itboat008.springboot.entity.User;
import com.itboat008.springboot.utils.PageRequest;
import com.itboat008.springboot.utils.PageResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
import java.util.Map;
public interface UserService {
User findById(Integer id);
List<User> findUsersByCompanyId(Integer companyId);
PageResult findUserByPage(PageRequest pageRequest);
void deleteById(Integer id);
void addUser(User user);
void updateUser(User user);
}
PageRequest:
package com.itboat008.springboot.utils;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Data
public class PageRequest {
private int pageNum;//当前页码
private int pageSize;//每页数量
}
PageResult:
package com.itboat008.springboot.utils;
import lombok.Data;
import java.util.List;
@Data
public class PageResult {
/**
* 当前页码
* */
private int pageNum;
/**
*每页数量
* */
private int pageSize;
/**
*记录总数
* */
private long totalSize;
/**
*页码总数
* */
private int totalPages;
/**
* 数据模型
*/
private List<?> content;
}
PageUtils:
package com.itboat008.springboot.utils;
import com.github.pagehelper.PageInfo;
public class PageUtils {
public static PageResult getPageResult(PageRequest pageRequest, PageInfo<?> pageInfo) {
PageResult pageResult = new PageResult();
pageResult.setPageNum(pageInfo.getPageNum());
pageResult.setPageSize(pageInfo.getPageSize());
pageResult.setTotalSize(pageInfo.getTotal());
pageResult.setTotalPages(pageInfo.getPages());
pageResult.setContent(pageInfo.getList());
return pageResult;
}
}
测试:
-
访问 http://localhost:8080/itboat008/user/findById?id=1
-
访问 http://localhost:8080/itboat008/user/findUsersByCompanyId/1
-
访问: http://localhost:8080/itboat008/user/findUserByPage
返回:
{
"pageNum": 3,
"pageSize": 2,
"totalSize": 6,
"totalPages": 3,
"content": [
{
"id": 5,
"userName": "欧阳锋",
"userCode": "ouyangfeng",
"companyId": 2
},
{
"id": 6,
"userName": "一灯",
"userCode": "yideng",
"companyId": 3
}
]
}
- 访问 http://localhost:8080/itboat008/user/deleteById?id=1
查询数据库:
-
访问: http://localhost:8080/itboat008/user/addUser
-
访问 http://localhost:8080/itboat008/user/updateUser