SpringBoot Mail 邮箱验证码
<dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-mail</artifactId > </dependency >
spring: mail: host: your.SMTP.host username: your_server_email@email.com password: your_passowrd
@Resource JavaMailSender sender; @PostMapping("/verification-email") public String sendVerificationEmail (@RequestParam String targetEmail, HttpSession session) { SimpleMailMessage message = new SimpleMailMessage (); message.setSubject(EMAIL_TITLE); int vCode = getVerificationCode(); session.setAttribute("vcode" , vCode); session.setAttribute("uemail" , email); message.setText(EMAIL_CONTEXT + code); message.setTo(targetEmail); message.setFrom(EMAIL_SERVEREMAIL); sender.send(message); return "发送成功" ; } @PostMapping("/register") public String register (@RequestParam String username, @RequestParam String email, @RequestParam String code, @RequestParam String password, HttpSession session) { String sessionCode = session.getAttribute("vcode" ).toString; String sessionEmail = session.getAttribute("uemail" ).toString; if (sessionCode == null ) { return "验证码为空" ; } if (!sessionCode.equals(code)) { return "验证码错误!" ; } if (!sessionEmail.equals(email)) { return "请获取验证码" ; } }
SpringBoot Validation 接口参数校验
Validation
<dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-validation</artifactId > </dependency >
方法1:参数前注解
@Validation @Controller public class SomeController { @PostMapping("/submit") public String submit (@Length(min = 3) String username, @Length(min = 8) String password) { } }
方法2:Entity注解
public class SomeEntity { @Length(min = 3) String username; } @Validation @Controller public class SomeController { @PostMapping("/submit") public String submit (@Valid String username, @Valid String password) { } }
Swagger 自动接口文档
SpringDoc
<dependency > <groupId > org.springdoc</groupId > <artifactId > springdoc-openapi-starter-webmvc-ui</artifactId > <version > 2.1.0</version > </dependency >
访问localhost/swagger-ui/index.html
即可查看文档。
添加文档说明
@Bean public OpenAPI springDocOpenAPI () { return new OpenAPI ().info(new Info () .title("Title of your Document" ) .description("Description of your Document" ) .version("Version" ) .license(new License ().name("License Name" ) .url("https://your.url" ))); } @Tag(name = "XX功能相关", description = "包括 ... 等操作。") public class SomeController { ... @ApiResponses({ @ApiResponse(responseCode = "200", description = "测试成功"), @ApiResponse(responseCode = "500", description = "测试失败") // 不同返回状态码描述 }) @Operation(summary = "请求用户数据测试接口") @ResponseBody @GetMapping("/hello") public String hello (@Parameter(description = "测试文本数据", example = "KFCvivo50") @RequestParam String text) { return "Hello World" ; } @Hidden private String helperMethod () { ... } } @Data @Schema(description = "用户信息实体类") public class User { @Schema(description = "用户编号") int id; @Schema(description = "用户名称") String name; @Schema(description = "用户邮箱") String email; @Schema(description = "用户密码") String password; }
生成环境一键关闭接口文档
springdoc: api-docs: enabled: false
JPA
优点:不用手写SQL
缺点:使用Hibernate重量级框架;完全屏蔽了底层SQL显示,对后期优化不友好;方法名太长
<dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-data-jpa</artifactId > </dependency >
实体类注解映射数据表
@Data @Entity @Table(name = "your_table_name") public class SomeEntity { @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @Id int id; @Column(name = "username") String username; @Column(name = "password") String password; }
使用Repository帮你编写sql
@Repository public interface AccountRepository extends JpaRepository <Account, Integer> { }@Resource AccountRepository repository; @Test void contextLoads () { Account account = new Account (); account.setUsername("小红" ); account.setPassword("1234567" ); System.out.println(repository.save(account).getId()); }
根据方法名自动匹配sql
@Repository public interface AccountRepository extends JpaRepository <Account, Integer> { List<Account> findAllByUsernameLike (String input) ; }
实体类关联外键
@Data @Entity @Table(name = "your_table_name") public class SomeEntity { @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @Id int id; @Column(name = "username") String username; @Column(name = "password") String password; @JoinColumn(name = "foreign_column_name") @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) AccountDetail detail; }
JPQL 自定义 SQL
@Repository public interface AccountRepository extends JpaRepository <Account, Integer> { @Transactional @Modifying @Query("update Account set password = ?2 where id = ?1") @Query(value = "update users set password = :pwd where username = :name", nativeQuery = true) int updatePasswordByUsername (@Param("name") String username, //我们可以使用@Param 指定名称 @Param("pwd") String newPassword) ;}
MyBatisPlus
是国内开发的用于增强MyBatis的非侵入型 框架。相当于JPA+MyBatis。
<dependency > <groupId > com.baomidou</groupId > <artifactId > mybatis-plus-boot-starter</artifactId > <version > 3.5.3.1</version > </dependency > <dependency > <groupId > com.mysql</groupId > <artifactId > mysql-connector-j</artifactId > </dependency >
映射实体类,继承BaseMapper
@Data @TableName("user") public class User { @TableId(type = IdType.AUTO) int id; @TableField("name") String name; @TableField("email") String email; @TableField("password") String password; } @Mapper public interface UserMapper extends BaseMapper <User> { }
复杂条件Wrapper
QueryWrapper<User> wrapper = new QueryWrapper <>(); wrapper .select("id" , "name" , "email" , "password" ) .ge("id" , 2 ) .orderByDesc("id" ); System.out.println(mapper.selectList(wrapper));
打印输出
mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
IService
@Service public interface UserService extends IService <User> { } @Service public class UserServiceImpl extends ServiceImpl <UserMapper, User> implements UserService {}
根据数据库生成代码
<dependency > <groupId > com.baomidou</groupId > <artifactId > mybatis-plus-boot-starter</artifactId > <version > 3.5.3.1</version > </dependency > <dependency > <groupId > com.baomidou</groupId > <artifactId > mybatis-plus-generator</artifactId > <version > 3.5.3.1</version > </dependency > <dependency > <groupId > org.apache.velocity</groupId > <artifactId > velocity-engine-core</artifactId > <version > 2.3</version > </dependency >
@Test void contextLoads () { FastAutoGenerator .create(new DataSourceConfig .Builder(dataSource)) .globalConfig(builder -> { builder.author("author" ); builder.commentDate("YY-MM-DD" ); builder.outputDir("src/main/java" ); }) .packageConfig(builder -> builder.parent("com.example" )) .strategyConfig(builder -> { builder .mapperBuilder() .mapperAnnotation(Mapper.class) .build(); }) .execute(); }