通过阅读本文之后,你将学会使用在几分钟内搭建好一个拥有基本功能的web后台开发框架。
一:使用idea创建spring boot应用
1.使用idea创建一个project,选择Spring Initializr选项,选择和团队一致的jdk版本之后next。
2.输入项目的包名
3.在依赖选项卡上勾选上Web即可
4.选择项目代码存放路径
5.最后你会看到下面这个样子的项目文件,等待idea加载完所需要的依赖即可。
二:配合使用JPA实现增删查改
1.为了更好的代码管理,做以下分层,并且注意:所有的代码都是和SpringBootDemoApplication在同一个文件夹下的,这点需要注意一下,如果不是在同一个文件夹下的话会报错。
2.在数据库中新建一张表:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for boss
-- ----------------------------
DROP TABLE IF EXISTS `boss`;
CREATE TABLE `boss` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
3.创建repository文件夹下,新建BossRepository类。(使用的是JPA)
package com.example.springbootdemo.repository;
import com.example.springbootdemo.model.Boss;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Repository
public interface BossRepository extends JpaRepository<Boss, Long> {
@Transactional
@Modifying(clearAutomatically = true)
@Query(value ="UPDATE boss SET name=?2 WHERE id =?1 ",nativeQuery = true)
Integer update(Long id,String name);
@Transactional
@Modifying(clearAutomatically = true)
@Query(value ="DELETE from boss WHERE id =?1 ",nativeQuery = true)
void deleteById(Long id);
Page<Boss> findAll(Pageable pageable);
List<Boss> findBossByNameLike(String name);
@Query(value ="select * from boss WHERE id =?1 ",nativeQuery = true)
Boss queryById(Long id);
}
4.在service文件夹下,新建BossService类:
package com.example.springbootdemo.service;
import com.example.springbootdemo.mapper.Boss2Mapper;
import com.example.springbootdemo.mapper.BossMapper;
import com.example.springbootdemo.model.Boss;
import com.example.springbootdemo.repository.BossRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import static com.github.pagehelper.page.PageMethod.startPage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class BossService {
@Autowired
private BossRepository bossRepository;
public List<Boss> findAll(){
return bossRepository.findAll();
}
/**
* @描述: 分页查询
* @作者 YangZhiRan
* @时间 2018/6/7 23:02
*/
public List<Boss> queryByPage(Integer page, Integer limit){
Integer start=(page-1)*limit;
Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC,"id"));
PageRequest pageRequest=new PageRequest(start,limit,sort);
Page<Boss> resultPage = bossRepository.findAll(pageRequest);
List<Boss> content = resultPage.getContent();
return content;
}
/**
* @描述: 新增
* @作者 YangZhiRan
* @时间 2018/6/7 22:56
*/
public Boolean insert(Boss boos){
Boss save = bossRepository.save(boos);
if( save != null){
return true;
}
return false;
}
/**
* @描述: 编辑
* @作者 YangZhiRan
* @时间 2018/6/7 22:56
*/
public Boolean update(Long id,String name){
Integer update = bossRepository.update(id, name);
return update>0?true:false;
}
/**
* @描述: 删除
* @作者 YangZhiRan
* @时间 2018/6/7 22:58
*/
public void delete(Long id){
bossRepository.deleteById(id);
}
/**
* @描述: 根据id查询
* @作者 YangZhiRan
* @时间 2018/6/7 23:05
*/
public Boss selectById(Long id){
return bossRepository.queryById(id);
}
/**
* @描述: 根据name查询
* @作者 YangZhiRan
* @时间 2018/6/7 23:05
*/
public List<Boss> selectByName(String name){
return bossRepository.findBossByNameLike("%"+name+"%");
}
}
5.在Controller文件夹下,新建MainController类:
package com.example.springbootdemo.controller;
import com.example.springbootdemo.model.Boss;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.springbootdemo.service.BossService;
import java.util.List;
@RestController
@RequestMapping(path="/test/demo")
public class MainController {
@Autowired
private BossService bossService;
@RequestMapping(path="/all")
public @ResponseBody List<Boss> getAllUsers() {
List<Boss> all = bossService.findAll();
return all;
}
@RequestMapping("/hello")
public String hello() {
return "hello,this is a springboot demo";
}
}
到此,一个基于Spring Boot配合JPA的基础的增删查改就完成了,接下来跑一下测试用例。
三:测试用例
1.Controller的测试用例:
package com.example.springbootdemo;
import com.example.springbootdemo.mapper.BossMapper;
import com.example.springbootdemo.model.Boss;
import com.example.springbootdemo.service.BossService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class SpringBootDemoApplicationTests {
@Test
public void contextLoads() {
}
private MockMvc mockMvc; // 模拟MVC对象,通过MockMvcBuilders.webAppContextSetup(this.wac).build()初始化。
@Autowired
private WebApplicationContext wac; // 注入WebApplicationContext
@Before // 在测试开始前初始化工作
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testFindAll() throws Exception {
String content = "";
this.mockMvc.perform(post("/test/demo/all").contentType(MediaType.APPLICATION_JSON).content(content)).andDo(print()).andExpect(status().isOk());
}
@Test
public void testAll() throws Exception {
MvcResult result = mockMvc.perform(post("/test/demo/all").param("pageNo", "1").param("pageSize", "2"))
.andExpect(status().isOk())// 模拟向testRest发送get请求
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;charset=UTF-8
.andReturn();// 返回执行请求的结果
System.out.println(result.getResponse().getContentAsString());
}
}
2.Service的测试用例:
package com.example.springbootdemo.service;
import com.example.springbootdemo.ApplicationTests;
import com.example.springbootdemo.model.Boss;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class TestBossService extends ApplicationTests {
@Autowired
private BossService bossService;
@Test
public void save(){
Boss boss =new Boss();
boss.setName("zhangXue");
Boolean insert = bossService.insert(boss);
System.out.print("结果:"+insert);
}
@Test
public void update(){
Boolean update = bossService.update(6L,"zhang xue");
System.out.print("结果:"+update);
}
@Test
public void queryByPage(){
List<Boss> bosses = bossService.queryByPage(1, 2);
System.out.print("结果:"+bosses);
}
@Test
public void selectByName(){
List<Boss> bosses = bossService.selectByName("ang");
System.out.print("结果:"+bosses);
}
@Test
public void delete(){
bossService.delete(6L);
}
}
四:基于mybatis的写法
大伙都知道,JPA对于简单的查询写起来是比较方便快捷的,但是如果是一些复杂点,还是大众的mybatis更为合适一点,这里会分别说明两种使用方式:一种是使用注解的方式,另外一种是使用xml配置文件的方式。
1.使用注解mybatis
package com.example.springbootdemo.mapper;
import com.example.springbootdemo.model.Boss;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Repository
public interface BossMapper {
@Select(value=" select * from boss where id = #{id}")
Boss queryById(@Param("id") Long id);
@SelectProvider(type = BossMapperMapper.class, method = "queryList")
List<Boss> queryList(Map<String,String> where);
class BossMapperMapper{
public String queryList(Map<String, Object> map){
String name = (String) map.get("name");
return new SQL() {
{
SELECT(" * ");
FROM("boss b ");
if(Objects.nonNull(name)) {
WHERE("b.name like '%" + name+"%'");
}
ORDER_BY(" b.id asc");
}
}.toString();
}
}
}
在SpringBootDemoApplication上要贴上一个扫描注解,用于扫描所有mybatis的接口。
@SpringBootApplication
@MapperScan("com.example.springbootdemo.mapper")
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
另外application.properties文件内容如下:
server.port=18888
mybatis.type-aliases-package=com.example.springbootdemo.model
mybatis.configuration.map-underscore-to-camel-case= true
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
2.使用xml配置文件
在application.properties文件中需要添加以下内容:
mybatis.mapper-locations=classpath:mapper/*.xml
创建接口类:
package com.example.springbootdemo.mapper;
import com.example.springbootdemo.model.Boss;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface Boss2Mapper {
List<Boss> select();
}
创建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.example.springbootdemo.mapper.Boss2Mapper" >
<sql id="BASE_TABLE">
boss
</sql>
<sql id="BASE_COLUMN">
id,name
</sql>
<select id="select" resultType="com.example.springbootdemo.model.Boss">
SELECT
<include refid="BASE_COLUMN"/>
FROM
<include refid="BASE_TABLE"/>
</select>
</mapper>
3.分别跑一下测试用例:
package com.example.springbootdemo.mapper;
import com.example.springbootdemo.ApplicationTests;
import com.example.springbootdemo.model.Boss;
import com.example.springbootdemo.repository.BossRepository;
import org.apache.ibatis.session.defaults.DefaultSqlSession;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestBossMapper extends ApplicationTests {
@Autowired
private BossMapper bossMapper;
@Test
public void queryById(){
Boss boss = bossMapper.queryById(1L);
System.out.print(boss);
}
@Test
public void queryList(){
Map where =new HashMap<String,String>();
where.put("name","ang");
List<Boss> boss = bossMapper.queryList(where);
System.out.print(boss);
}
}
package com.example.springbootdemo.service;
import com.example.springbootdemo.ApplicationTests;
import com.example.springbootdemo.model.Boss;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class TestBossService extends ApplicationTests {
@Autowired
private BossService bossService;
@Test
public void queryList(){
List<Boss> bosses = bossService.queryList(1,2);
System.out.print("结果:"+bosses);
List<Boss> select = bossService.select();
System.out.print("结果:"+select);
}
}
最后贴一下整个项目的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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.jayway.restassured/spring-mock-mvc -->
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>spring-mock-mvc</artifactId>
<version>2.9.0</version>
<scope>test</scope>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.6.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.2.4</version>
</dependency>
<!--pagehelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
本文案列代码下载:代码下载