idea创建Springboot工程
1、创建Springboot工程,使用脚手架的方式
2、选择Springboot的版本和使用到的依赖
3、创建后查看项目的目录结构
因为我这里使用的是阿里云地址创建,所以会有一些测试文件
地址:https://start.aliyun.com/
4、修改配置文件后缀名。.yml
5、数据库的配置
6、数据库配置完就可以启动项目了
测试,到此创建了一口空的Springboot工程
总结:创建Spring Boot项目
1、使用Spring Initializr(https://start.spring.io/)创建一个新的Spring Boot项目。
2、选择所需的依赖,包括Spring Web和MyBatis。
3、配置数据库连接信息,包括数据库URL、用户名和密码。
下面用Springboot整合Mybatis
1、maven配置
2、整合步骤就不细说了,这里把完整代码附上,也可以直接下载文件。
3、目录结构(主要是这些文件,有多余的文件就打码了,不想删了)
application.yml—Springboot的配置文件
server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/qing?serverTimezone=GMT%2b8
username: root
password: 123456
mvc:
pathmatch:
matching-strategy: ant_path_matcher
mybatis:
mapper-locations: classpath:mapper/*.xml #扫描所有mybatis的xml文件
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
resources/mapper/UserMapper.xml—写sql语句的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.xiejie.mapper.UserMapper">
<update id="update">
update sys_user
<set>
<if test="username != null">
username = #{username},
</if>
<!-- <if test="password != null">-->
<!-- password = #{password}-->
<!-- </if>-->
<if test="nickname != null">
nickname = #{nickname},
</if>
<if test="email != null">
email = #{email},
</if>
<if test="phone != null">
phone = #{phone},
</if>
<if test="address != null">
address = #{address}
</if>
</set>
<where>
id = #{id}
</where>
</update>
</mapper>
DemoApplication.java-----启动类
package com.xiejie;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
config包下的文件
com/xiejie/config/CorsConfig.java 解决跨域问题,现在没有前端代码,可以暂时不加这部分
package com.xiejie.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
// 当前跨域请求最大有效时长。这里默认1天
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://localhost:8080"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
SwaggerConfig.java------方便进行接口测试
package com.xiejie.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@MapperScan("com.xiejie.mapper")
public class SwaggerConfig {
@Bean
public Docket customDocket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//
.apis(RequestHandlerSelectors.basePackage("com.xiejie.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口测试")
.version("1.0.0")
.build();
}
}
controller包下的文件
UserController .java
package com.xiejie.controller;
import com.xiejie.entity.User;
import com.xiejie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
// 新增和修改
@PostMapping
public Result save(@RequestBody User user) {
boolean flag = userService.save(user);
return flag ? Result.success(Code.SAVE_OK) :Result.failure(Code.SAVE_ERR,"保存失败");
}
@PutMapping
public Result update(@RequestBody User user){
boolean flag = userService.update(user);
return flag ? Result.success(Code.UPDATE_OK) : Result.failure(Code.UPDATE_ERR, "更新失败");
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
boolean flag = userService.delete(id);
return flag ? Result.success(Code.DELETE_OK):Result.failure(Code.DELETE_ERR, "删除失败");
}
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id){
User user = userService.getById(id);
if (user != null) {
return Result.success(user);
} else {
return Result.failure(Code.GET_ERR, "数据查询失败,请重试");
}
}
@GetMapping
public Result getAll(){
List<User> userList = userService.getAll();
return userList !=null? Result.success(userList) :Result.failure(Code.GET_ERR, "数据查询失败,请重试!!");
}
}
Code.java
package com.xiejie.controller;
public class Code {
public static final Integer SAVE_OK = 20011;
public static final Integer DELETE_OK = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERR = 20010;
public static final Integer DELETE_ERR = 20020;
public static final Integer UPDATE_ERR = 20030;
public static final Integer GET_ERR = 20040;
public static final Integer SYSTEM_ERR = 50001;
public static final Integer SYSTEM_TIMEOUT_ERR = 50002;
public static final Integer SYSTEM_UNKNOW_ERR = 59999;
public static final Integer BUSINESS_ERR = 60002;
}
package com.xiejie.controller;
import com.xiejie.exception.BusinessException;
import com.xiejie.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException ex){
//记录日志
//发送消息给运维
//发送邮件给开发人员,ex对象发送给开发人员
return new Result(ex.getCode(),null,ex.getMessage());
}
@ExceptionHandler(BusinessException.class)
public Result doBusinessException(BusinessException ex){
return new Result(ex.getCode(),null,ex.getMessage());
}
@ExceptionHandler(Exception.class)
public Result doOtherException(Exception ex){
//记录日志
//发送消息给运维
//发送邮件给开发人员,ex对象发送给开发人员
return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
}
}
package com.xiejie.controller;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
private Object data;
private Integer code;
private String msg;
public Result(Object data, Integer code) {
this.data = data;
this.code = code;
}
public Result(Integer code) {
this.code = code;
}
public static Result success(Integer code) {
return new Result(code);
}
public static Result success(Object data) {
return new Result(data, 200, null);
}
public static Result failure(Integer code, String msg) {
return new Result(null, code, msg);
}
}
entity包下的文件
package com.xiejie.entity;
import java.io.Serializable;
import java.time.LocalDateTime;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
/**
* <p>
*
* </p>
*
* @author xiejie
* @since 2024-01-27
*/
@Getter
@Setter
@ApiModel(value = "User对象", description = "")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("id")
private Integer id;
@ApiModelProperty("用户名")
private String username;
@ApiModelProperty("密码")
private String password;
@ApiModelProperty("昵称")
private String nickname;
@ApiModelProperty("邮箱")
private String email;
@ApiModelProperty("电话")
private String phone;
@ApiModelProperty("地址")
private String address;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("头像")
private String avatarUrl;
@ApiModelProperty("角色")
private String role;
}
mapper包下的文件
package com.xiejie.mapper;
import com.xiejie.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
@Insert("INSERT into sys_user(username, password,nickname,email,phone,address,avatar_url,role) VALUES (#{username}, #{password}," +
" #{nickname}, #{email},#{phone}, #{address}, #{avatarUrl}, #{role})")
int save(User user);
int update(User user);
@Delete("delete from sys_user where id = #{id}")
Integer delete(@Param("id") Integer id);
@Select("select * from sys_user where id = #{id} ")
User getById(Integer id);
@Select("SELECT * from sys_user")
List<User> getAll();
}
service包下的文件
package com.xiejie.service;
import com.xiejie.entity.User;
import java.awt.print.Book;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author xiejie
* @since 2024-01-27
*/
public interface UserService {
/**
*保存
* @param user 入参
* @return boolean
**/
public boolean save(User user);
/**
*修改
* @param user 入参
* @return boolean
**/
public boolean update(User user);
/**
*按id删除
* @param id 入参
* @return boolean
**/
public boolean delete(Integer id);
/**
*按id查询
* @param id 入参
* @return User
**/
public User getById(Integer id);
/**
* 查询全部
* @param 入参
* @return List<User>
**/
public List<User> getAll();
}
package com.xiejie.service.impl;
import com.xiejie.entity.User;
import com.xiejie.mapper.UserMapper;
import com.xiejie.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
private UserMapper userMapper;
@Override
public boolean save(User user) {
return userMapper.save(user)>0;
}
@Override
public boolean update(User user) {
return userMapper.update(user) >0;
}
@Override
public boolean delete(Integer id) {
return userMapper.delete(id)>0;
}
@Override
public User getById(Integer id) {
return userMapper.getById(id);
}
@Override
public List<User> getAll() {
return userMapper.getAll();
}
}
总结:
1、创建MyBatis映射器(Mapper)
创建MyBatis映射器接口和XML文件。例如,你可以创建一个UserMapper.java接口和对应的UserMapper.xml文件。
在UserMapper.java中定义数据库操作的方法,例如查询、插入、更新等。
在UserMapper.xml中编写SQL语句以及映射关系。
2、创建实体类
创建与数据库表对应的实体类,在该类中定义字段以及对应的getter和setter方法。
3、编写Service层
创建一个Service类,用于编写业务逻辑。
在Service类中注入对应的Mapper,并实现业务方法。
4、编写Controller层
创建一个Controller类,用于处理HTTP请求。
在Controller中调用Service层的方法,并返回相应的结果。
5、运行项目
使用Maven或Gradle构建项目。
运行Spring Boot应用程序,并访问定义的API端点来测试功能