1.创建
数据库创建
依赖引入
<!-- mybatis起步依赖--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.3</version></dependency> <!-- mysql驱动依赖--><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId></dependency> //web依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
配置文件
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mybatisusername: rootpassword: 123
实体类
1.报错:java: 无法推断com.itheima.springbootconfigfile.pojo.Result<>的类型参数 原因: 无法推断类型变量 T (实际参数列表和形式参数列表长度不同)
修改:在Result类中写上构造方法,set(),get(),toString()
2.lombok:编译阶段,自动生成set,get,toString()或者
@NoArgsConstructor @AllArgsConstructor:pom.xml+注解 :
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId> </dependency>
运行,报错:[ERROR] Error executing Maven. [ERROR] The specified user settings file does not exist: C:\Users\enjoy\.m2\settings.xml
修改:选择使用IDEA自带的Maven:对号不选
运行成功!
启动类
package com.itheima.springbootconfigfile;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication //@MapperScan("com.itheima.springbootconfigfile") public class BigEventApplication {public static void main(String[] args) {SpringApplication.run(BigEventApplication.class,args);} }
2.注册,参数校验(前端校验,方便客户使用,后端校验,更安全):
package com.itheima.springbootconfigfile.controller;import com.itheima.springbootconfigfile.pojo.Result;
import com.itheima.springbootconfigfile.pojo.User;
import com.itheima.springbootconfigfile.service.UserService;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;// public User findById(Integer id){
// return userService.findById(id);
// }//注册@GetMapping("/register")public Result register(String username, String password){//参数校验if(username!=null&&username.length()>=5&&username.length()<=16&&password!=null&&password.length()>=5&&password.length()<=16){//用户名是否存在User user=userService.findByUserName(username);if(user==null){//不存在则注册userService.register(username,password);return Result.success();//输出操作成功} else{//若已存在return Result.success("用户名已占用");}//参数校验}else{return Result.error("参数不合法");}}}
太繁琐,->SpringValidation
<!-- validation依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>
package com.itheima.springbootconfigfile.controller;import com.itheima.springbootconfigfile.pojo.Result;
import com.itheima.springbootconfigfile.pojo.User;
import com.itheima.springbootconfigfile.service.UserService;import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/user")
@Validated
public class UserController {@Autowiredprivate UserService userService;// public User findById(Integer id){
// return userService.findById(id);
// }//注册@GetMapping("/register")public Result register(@Pattern(regexp="^\\S{5,16}$")String username, @Pattern(regexp = "^\\S{5,16}$") String password){//参数校验
//
// if(username!=null&&username.length()>=5&&username.length()<=16&&
// password!=null&&password.length()>=5&&password.length()<=16
// ){//用户名是否存在User user=userService.findByUserName(username);if(user==null){//不存在则注册userService.register(username,password);return Result.success();//输出操作成功} else{//若已存在return Result.success("用户名已占用");}//参数校验
// }else{
// return Result.error("参数不合法");
//
// }}}
1.表示匹配任何非空白字符。注意,这里使用了双反斜杠 \\
,因为在 Java 字符串中,反斜杠 \
是转义字符,所以需要用 \\
来表示一个反斜杠。
2.{5,16}
:表示前面的字符(这里是 \S
)必须出现 5 到 16 次。也就是说,字符串的长度必须在 5 到 16 个非空白字符之间。
报错:500,参数校验出现异常:全局异常处理
修改:
package com.itheima.springbootconfigfile.exception;import com.itheima.springbootconfigfile.pojo.Result;import org.springframework.util.StringUtils;
//
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;@RestControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public Result handleException(Exception e){e.printStackTrace();//错误输出出来return Result.error(StringUtils.hasLength(e.getMessage())?e.getMessage():"操作失败");//错误原因}
}
1.@RestControllerAdvice
是 Spring Boot 中用于定义全局异常处理器的注解,它是 @ControllerAdvice
和 @ResponseBody
的组合
2.StringUtils.hasLength
是 Apache Commons Lang 库中的一个工具方法,用于判断字符串是否具有长度(即是否非空且不为空字符串):
StringUtils.hasLength(e.getMessage())?e.getMessage():"操作失败"
是否有错误异常信息,有则输出,无则输出"操作失败"
第一次修改后:驼峰命名与下划线命名
仍报错
发现IDEA连接数据库,不用先在NAVICAT写,在IDEA写后,NAVICAT会自动出现:
第二次修改:发现IDEA连了两个database,里边都有user表(mybatis-user-name,big_event-user-username),把database mybatis去除,成功
后来发现,应该是该application.yml的url:
运行截图:
部分代码展示:
userController:
package com.itheima.springbootconfigfile.controller;import com.itheima.springbootconfigfile.pojo.Result;
import com.itheima.springbootconfigfile.pojo.User;
import com.itheima.springbootconfigfile.service.UserService;import com.itheima.springbootconfigfile.utils.MailUtil1;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/user")
@Validated
public class UserController {@Autowiredprivate UserService userService;// public User findById(Integer id){
// return userService.findById(id);
// }//注册@GetMapping("/register")public Result register(@Pattern(regexp="^\\S{5,16}$")String username, @Pattern(regexp = "^\\S{5,16}$") String password){//参数校验
//
// if(username!=null&&username.length()>=5&&username.length()<=16&&
// password!=null&&password.length()>=5&&password.length()<=16
// ){//用户名是否存在User user=userService.findByUserName(username);if(user==null){//不存在则注册userService.register(username,password);return Result.success();//输出操作成功} else{//若已存在return Result.error("用户名已占用");}//参数校验
// }else{
// return Result.error("参数不合法");
//
// }}}
userMapper:
package com.itheima.springbootconfigfile.mapper;import com.itheima.springbootconfigfile.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Select;import java.util.Date;@Mapper
public interface UserMapper {@Select("select * from user where id=#{id}")public User findById(Integer id);//注册@Select("select * from user where username=#{username}")public User findByUserName(String username);@Insert("insert into user(username,password,createTime,updateTime) values (#{username},#{password},now(),now())")void add(String username, String password);}