// %JAVA_HOME% %MAVEN_HOME%[conf/settings.xml repository] mvn spring-boot:run
// resources 目录新建 banner.txt,把水印文案写进去,启动项目就会显示你自定义的水印
// spring-boot-starter-web 依赖
// mybatis-plus-boot-starter 依赖
// mysql-connector-j 依赖
// lombok 依赖
// spring-boot-devtools 依赖
// spring-boot-configuration-processor 依赖
// spring-boot-starter-data-redis 依赖
// spring-boot-starter-mail 依赖
// MybatisX 插件
@Controller @Service @Component
@Autowired - byType / @Resource - byName
@Slf4j log -> trace debug info warn error
@SpringBootApplication
@MapperScan("com.xxx.usercenter.mapper")
public class UserCenterApplication {
public static void main(String[] args) {
SpringApplication.run(UserCenterApplication.class, args);
}
}
@Data
@TableName("table")
public class User implements Serializable {
private static final long serialVersionUID = 1L; // 手写 - 默认JDK自动分配
@TableId(value="id", type=IdType.AUTO) // 主键自增 分库分表用IdType.ASSIGN_ID
private Long id;
@TableField("user_name")
private String userName;
@TableField("enabled")
private Boolean enabled;
@TableField("salary")
private BigDecimal salary;
// 逻辑删除 删除时候改为1
@TableLogic(value="0", delval="1")
private Integer deleted;
// 非库表字段
@TableField(exist=false)
private String displayName;
}
// LambdaQueryWrapper<User> LambdaUpdateWrapper<User>
wrapper
.eq(User::getUserName, "小翊") // 等于
.ne(User::getId, 1) // 不等于
.gt(User::getAge, 18) // 大于
.ge(User::getAge, 18) // 大于等于
.lt(User::getAge, 60) // 小于
.le(User::getAge, 60) // 小于等于
.like(User::getUserName, "小") // 模糊
.between(User::getAge, 18, 30) // 区间
.in(User::getId, List.of(1, 2, 3)) // 包含
.isNotNull(User::getEmail) // 非空
.orderByAsc(User::getId) // 升序
.orderByDesc(User::getId) // 降序
.and(child -> child.eq(User::getSex, 1)) // 且
.or(child -> child.eq(User::getSex, 2)); // 或
@Transactional(rollbackFor=Exception.class)
public void transfer() {
// 通常回滚 INSERT / UPDATE / DELETE
// 切勿吞掉异常 异常触发回滚 - 可主动抛出
}
// 乐观锁
@Version // PO 添加属性
@TableField("version")
private Long version;
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
// 只支持 updateById(entity)、update(entity, wrapper)
// 返回rows=0表示版本已经被他人修改 需要重试
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
// 乐观锁和悲观锁的使用都建议通过事务调用
// 悲观锁
public interface UserMapper extends BaseMapper<User> {
// 共享锁: 读出来, 允许别人也读, 但不允许别人改
@Select("SELECT * FROM user WHERE id = #{id} FOR SHARE")
User selectByIdForShare(@Param("id") Long id);
// 排他锁: 读出来, 别人既不能读也不能改, 只有我能改
@Select("SELECT * FROM user WHERE id = #{id} FOR UPDATE")
User selectByIdForUpdate(@Param("id") Long id);
}
// 分页查询
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
// 使用
Page<User> page = new Page<>(current, size); // 页码从 1 开始
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.like(username != null, User::getUserName, username);
IPage<User> result = userService.page(page, queryWrapper);
List<User> userList = result.getRecords(); // 当前页数据
long total = result.getTotal(); // 总记录数
long pages = result.getPages(); // 总页数
long cur = result.getCurrent(); // 当前页
if (result.hasNext()) { // 是否还有下一页
System.out.println("还有下一页");
}
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
private final UserLoginLogMapper userLoginLogMapper;
private final VerificationCodeService verificationCodeService;
}
// application.yml - yml配置文件对于0开头数据认定为八进制 - 使用双引号包裹
spring:
profiles:
active: dev # 激活环境:dev / prod
application:
name: application-name
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/dbname?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
username: root
password: passwd
session:
store-type: redis # session 存 redis,分布式会话共享
data:
redis:
url: redis://:password@127.0.0.1:6379
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 2
max-wait: 2000ms
mail:
host: smtp.163.com
port: 465
username: xxx@163.com
password: 授权码
properties:
mail:
smtp:
ssl:
enable: true
auth: true
server:
address: 0.0.0.0
port: 8080
servlet:
context-path: /api # 全局路径前缀
session:
timeout: 604800
cookie:
name: JSESSIONID
secure: false
http-only: true
domain: domain.cn # 多子域名共享 cookie;不配置则自动分配当前访问域名
path: / # 默认值,整个站点都带 cookie
mybatis-plus:
configuration:
use-deprecated-executor: false
map-underscore-to-camel-case: true # 驼峰转下划线
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印 SQL 日志
logging:
file:
# 相对路径
name: logs/app.log
level:
root: info
com.xxx.xx: debug