Java
Java
# properties
将配置文件中的属性绑定到类的字段
@Component
@ConfigurationProperties(prefix = "sky.jwt")
@Data
public class JwtProperties {
/**
* 管理端员工生成jwt令牌相关配置
*/
private String adminSecretKey;
private long adminTtl;
private String adminTokenName;
/**
* 用户端微信用户生成jwt令牌相关配置
*/
private String userSecretKey;
private long userTtl;
private String userTokenName;
}
application.yml
sky:
jwt:
# 设置jwt签名加密时使用的秘钥
admin-secret-key: itcast
# 设置jwt过期时间
admin-ttl: 7200000
# 设置前端传递过来的令牌名称
admin-token-name: token
# MP
# 分页
MP
Page<Blog> page = blogService.query()
.eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
Mybatis——PageHelper
PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);//后续定义
PageHelper.startPage(pageNum,pageSize);
PageBean<Article> pageBean = new PageBean<>();
Map<String,Object> map = ThreadLocalUtil.get();
Integer userId = (Integer) map.get("id");
List<Article> articles = articleMapper.list(userId,categoryId,state);
PageInfo<Article> pageInfo = new PageInfo<>(articles);
pageBean.setTotal(pageInfo.getTotal());
pageBean.setItems(pageInfo.getList());
MybatisX插件:mapper和mapper.xml
MybatisPlus插件:可以直接生成类:实体类、controller、service、serviceimpl、mapper
# Mybatis映射文件动态sql
parameterType是指定传输的参数数据类型
resultType:指定从 SQL 查询返回的结果集应该映射到的 Java 类型。MyBatis 将会自动将每一行映射到该类型的实例上。
mybatis:
#mapper配置文件
mapper-locations: classpath:mapper/*.xml
#设置动态sql的别名,就不用写包的全路径
type-aliases-package: com.sky.entity
update设置的动态sql可以给所有update调用,设置别名后可以直接用类名
<?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.sky.mapper.EmployeeMapper">
<select id="pageQuery" resultType="com.sky.entity.Employee">
select * from employee
<where>
<if test="name != null and name != ''">
and name like concat('%',#{name},'%')
</if>
</where>
order by create_time desc
</select>
<update id="update" parameterType="Employee">
update employee
<set>
<if test="name != null">name = #{name},</if>
<if test="username != null">username = #{username},</if>
<if test="password != null">password = #{password},</if>
<if test="phone != null">phone = #{phone},</if>
<if test="sex != null">sex = #{sex},</if>
<if test="idNumber != null">id_Number = #{idNumber},</if>
<if test="updateTime != null">update_Time = #{updateTime},</if>
<if test="updateUser != null">update_User = #{updateUser},</if>
<if test="status != null">status = #{status},</if>
</set>
where id = #{id}
</update>
</mapper>
useGeneratedKeys,插入数据时返回由数据库内部生成的主键,用keyProperty接收生成键值的目标属性名
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into dish (name, category_id, price, image, description, create_time, update_time, create_user,update_user, status)
values (#{name}, #{categoryId}, #{price}, #{image}, #{description}, #{createTime}, #{updateTime}, #{createUser}, #{updateUser}, #{status})
</insert>
@Insert("insert into user(name,age)values(#{name},#{age})")
@0ptions(useGeneratedKeys = true,keyProperty = "id")
void insert(User user);
foreach
<insert id="insertBatch">
insert into dish_flavor (dish_id, name, value) VALUES
<foreach collection="flavors" item="df" separator=",">
(#{df.dishId},#{df.name},#{df.value})
</foreach>
</insert>
# removeByIds和removeBatchByIds
removeByIds: 用in(ids...)
removeBatchByIds: where id = x
# # 批量新增
MybatisPlus
的批处理Batch是基于PrepareStatement
的预编译模式,然后批量提交,最终在数据库执行时还是会有多条insert语句,逐条插入数据。SQL类似这样:
Preparing: INSERT INTO user ( username, password, phone, info, balance, create_time, update_time ) VALUES ( ?, ?, ?, ?, ?, ?, ? )
Parameters: user_1, 123, 18688190001, "", 2000, 2023-07-01, 2023-07-01
Parameters: user_2, 123, 18688190002, "", 2000, 2023-07-01, 2023-07-01
Parameters: user_3, 123, 18688190003, "", 2000, 2023-07-01, 2023-07-01
而如果想要得到最佳性能,最好是将多条SQL合并为一条,像这样:
INSERT INTO user ( username, password, phone, info, balance, create_time, update_time )
VALUES
(user_1, 123, 18688190001, "", 2000, 2023-07-01, 2023-07-01),
(user_2, 123, 18688190002, "", 2000, 2023-07-01, 2023-07-01),
(user_3, 123, 18688190003, "", 2000, 2023-07-01, 2023-07-01),
(user_4, 123, 18688190004, "", 2000, 2023-07-01, 2023-07-01);
需要重写批处理的statement
语句:
修改项目中的application.yml文件,在jdbc的url后面添加参数&rewriteBatchedStatements=true
:
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: MySQL123
# 循环依赖DB静态工具
MP的Service中的循环依赖可以通过使用DB静态工具来解决
# 逻辑删除
- 在
application.yml
中配置逻辑删除字段:
mybatis-plus:
global-config:
db-config:
logic-delete-field: deleted # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
- 在实体类中用@TableLogin指定字段为逻辑删除字段
# 枚举处理器
# 配置枚举处理器
在application.yaml文件中添加配置:
mybatis-plus:
configuration:
default-enum-type-handler: com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler
# 定义枚举
为了使数据库与实体类的枚举字段对应,需要用注解@EnumValue指定字段
使页面查询结果也是枚举格式,我们需要给使用注解@JsonValue指定JSON格式化展示的字段:
package com.itheima.mp.enums;
import com.baomidou.mybatisplus.annotation.EnumValue;
import lombok.Getter;
@Getter
public enum UserStatus {
NORMAL(1, "正常"),
FREEZE(2, "冻结")
;
@EnumValue
private final int value;
@JsonValue
private final String desc;
UserStatus(int value, String desc) {
this.value = value;
this.desc = desc;
}
}
# Json类型处理器
# 分页插件
先定义配置类
# 构造器注入
可以使用lombok的 RequiredArgsConsturctor,依赖注入使用final修饰的属性
# 启动多个服务
https://www.bilibili.com/video/BV1S142197x7?spm_id_from=333.788.player.switch&vd_source=5063386180163934afae66c4e87325ac&p=48 的6:00
# 日期格式化**
解决方式:
1). 方式一
在属性上加上注解,对日期进行格式化

但这种方式,需要在每个时间属性上都要加上该注解,使用较麻烦,不能全局处理。
2). 方式二(推荐 )
在WebMvcConfiguration中扩展SpringMVC的消息转换器,统一对日期类型进行格式处理
/**
* 扩展Spring MVC框架的消息转化器
* @param converters
*/
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
log.info("扩展消息转换器...");
//创建一个消息转换器对象
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
//需要为消息转换器设置一个对象转换器,对象转换器可以将Java对象序列化为json数据
converter.setObjectMapper(new JacksonObjectMapper());
//将自己的消息转化器加入容器中
converters.add(0,converter);
}
# 知识
# lambda表达式
# 链式编程
每个方法都返回当前对象(this
),使得方法调用可以“链”在一起。
# Build
lombok提供builder可以直接用.builder().....build()创建一个对象
# 函数式接口(四种)
# Function函数型接口
@FunctionalInterface
public interface Function<T,R>{
R apply(T t);
}
# Predicate断定型接口
@FunctionalInterface
public interface Predicate<T>{
boolean test(T t);
}
# Consumer消费型接口
@FunctionalInterface
public interface Consumer<T>{
void accept(T t);
}
# supplier供给型接口
@FunctionalInterface
publlic interface supplier<T>{
T get();
}
# Stream流式计算
# 事务
操作两张表时需要开启事务,在SpringBootApplication中添加EnableTransactionManagement
#
# Q
1.分页Result要封装吗
2.通过异常捕获还是直接用result返回前端msg