mirror of
https://github.com/Estom/notes.git
synced 2026-11-29 23:55:37 +08:00
博客系统
This commit is contained in:
@@ -2,11 +2,13 @@
|
||||
|
||||
> 数据库与数据源不是同一个东西。。。
|
||||
> 三层关键概念需要理解
|
||||
>
|
||||
> 1. 数据库驱动mysql、hsqldb
|
||||
> 2. 数据源datasource和数据库连接池Harica、Druid
|
||||
> 3. 数据库操作工具JDBCTemplates、Mybatis
|
||||
|
||||
### 数据源配置
|
||||
|
||||
pom.xml
|
||||
|
||||
```
|
||||
@@ -17,7 +19,9 @@ pom.xml
|
||||
```
|
||||
|
||||
### 嵌入式数据库驱动
|
||||
|
||||
嵌入式数据库支持:H2、HSQL、Derby。不需要任何配置,被集成到springboot的jar包当中。
|
||||
|
||||
```
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
@@ -36,7 +40,9 @@ pom.xml
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
* 配置数据源信息
|
||||
|
||||
```
|
||||
spring.datasource.url=jdbc:mysql://localhost:3306/test
|
||||
spring.datasource.username=dbuser
|
||||
@@ -44,11 +50,20 @@ spring.datasource.password=dbpass
|
||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver//定义了数据引擎
|
||||
```
|
||||
|
||||
### 自动配置
|
||||
|
||||
* DataSourceAutoConfiguration
|
||||
* 底层自动配置了默认的数据源Hicari
|
||||
* DataSourceTransactionAutoConfiguration
|
||||
* JdbcTemplateAutoConfiguration
|
||||
* JndiAutoConfiguration
|
||||
|
||||
### 连接JNDI数据源
|
||||
|
||||
JNDI,避免了程序与数据库之间的紧耦合,是指更容易配置和部署。
|
||||
|
||||
JNDI不需要用户使用java代码与数据库建立连接,而是将连接交给应用服务器进行管理。java负责与应用服务器上的JNDI通信。
|
||||
|
||||
```
|
||||
spring.datasource.jndi-name=java:jboss/datasources/customers
|
||||
```
|
||||
@@ -56,6 +71,7 @@ spring.datasource.jndi-name=java:jboss/datasources/customers
|
||||
## 2 JdbcTemplate操作数据库
|
||||
|
||||
### 准备数据库
|
||||
|
||||
```
|
||||
CREATE TABLE `User` (
|
||||
`name` varchar(100) COLLATE utf8mb4_general_ci NOT NULL,
|
||||
@@ -64,6 +80,7 @@ CREATE TABLE `User` (
|
||||
```
|
||||
|
||||
### 编写领域对象
|
||||
|
||||
并不是MVC的一部分。数据层,实现数据访问
|
||||
|
||||
```
|
||||
@@ -78,9 +95,11 @@ public class User {
|
||||
```
|
||||
|
||||
### 编写数据访问对象
|
||||
|
||||
并非MVC的一部分。服务层,实现业务逻辑
|
||||
|
||||
* 定义包含插入、删除、查询的抽象接口UserService
|
||||
|
||||
```java
|
||||
public interface UserService {
|
||||
|
||||
@@ -167,7 +186,9 @@ public class UserServiceImpl implements UserService {
|
||||
```
|
||||
|
||||
### 编写单元测试用例
|
||||
|
||||
创建对UserService的单元测试用例,通过创建、删除和查询来验证数据库操作的正确性。
|
||||
|
||||
```java
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@@ -208,4 +229,4 @@ public class Chapter31ApplicationTests {
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
> 对象关系映射模型Hibernate。用来实现非常轻量级的对象的封装。将对象与数据库建立映射关系。实现增删查改。
|
||||
> MyBatis与Hibernate非常相似。对象关系映射模型ORG。java对象与关系数据库映射的模型。
|
||||
|
||||
|
||||
|
||||
|
||||
## 1 配置MyBatis
|
||||
|
||||
### 最佳实践
|
||||
@@ -16,8 +13,7 @@
|
||||
● 复杂方法编写mapper.xml进行绑定映射
|
||||
● @MapperScan("com.atguigu.admin.mapper") 简化,其他的接口就可以不用标注@Mapper注解
|
||||
|
||||
|
||||
### 在pom.xml中添加MyBatis依赖
|
||||
### 添加MyBatis依赖
|
||||
|
||||
```
|
||||
<dependency>
|
||||
@@ -33,6 +29,7 @@
|
||||
```
|
||||
|
||||
### 配置数据库连接
|
||||
|
||||
在application.properties中配置mysql的链接配置
|
||||
|
||||
```sh
|
||||
@@ -42,7 +39,7 @@ spring.datasource.password=
|
||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
```
|
||||
|
||||
### 创建关系数据表
|
||||
### 创建数据表
|
||||
|
||||
```sql
|
||||
CREATE TABLE `User` (
|
||||
@@ -53,7 +50,7 @@ CREATE TABLE `User` (
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
|
||||
```
|
||||
|
||||
### 创建数据表的java对象
|
||||
### 创建java对象
|
||||
|
||||
```java
|
||||
@Data
|
||||
@@ -72,17 +69,16 @@ public class User {
|
||||
}
|
||||
```
|
||||
|
||||
### MyBatis参数传递
|
||||
|
||||
## 2 MyBatis参数传递
|
||||
|
||||
### 使用@Param参数传递
|
||||
使用@Param参数传递
|
||||
|
||||
```
|
||||
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
|
||||
int insert(@Param("name") String name, @Param("age") Integer age);
|
||||
```
|
||||
|
||||
### 使用map 传递参数
|
||||
使用map 传递参数
|
||||
|
||||
```
|
||||
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
|
||||
@@ -94,13 +90,14 @@ map.put("age", 40);
|
||||
userMapper.insertByMap(map);
|
||||
```
|
||||
|
||||
### 使用普通java对象
|
||||
使用普通java对象
|
||||
|
||||
```
|
||||
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
|
||||
int insertByUser(User user);
|
||||
```
|
||||
## 3 注解模式
|
||||
|
||||
## 2注解模式
|
||||
|
||||
### 创建数据表的操作接口
|
||||
|
||||
@@ -116,7 +113,9 @@ public interface UserMapper {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### 增删改查操作
|
||||
|
||||
```java
|
||||
public interface UserMapper {
|
||||
|
||||
@@ -133,7 +132,9 @@ public interface UserMapper {
|
||||
void delete(Long id);
|
||||
}
|
||||
```
|
||||
|
||||
对增删查改的调用
|
||||
|
||||
```java
|
||||
@Transactional
|
||||
@RunWith(SpringRunner.class)
|
||||
@@ -163,9 +164,12 @@ public class ApplicationTests {
|
||||
}
|
||||
```
|
||||
|
||||
## 4 XML方式
|
||||
## 3 XML方式
|
||||
|
||||
### 创建Mapper文件
|
||||
|
||||
在应用主类中增加mapper的扫描包配置:
|
||||
|
||||
### 在应用主类中增加mapper的扫描包配置:
|
||||
```
|
||||
@MapperScan("com.didispace.chapter36.mapper")
|
||||
@SpringBootApplication
|
||||
@@ -178,7 +182,8 @@ public class Chapter36Application {
|
||||
}
|
||||
```
|
||||
|
||||
### Mapper包下创建User表
|
||||
Mapper包下创建User表
|
||||
|
||||
```
|
||||
public interface UserMapper {
|
||||
|
||||
@@ -189,12 +194,13 @@ public interface UserMapper {
|
||||
}
|
||||
```
|
||||
|
||||
### 在配置文件中通过mybatis.mapper-locations参数指定xml配置的位置
|
||||
在配置文件中通过mybatis.mapper-locations参数指定xml配置的位置
|
||||
|
||||
```
|
||||
mybatis.mapper-locations=classpath:mapper/*.xml
|
||||
```
|
||||
### xml配置目录下创建User表的mapper配置
|
||||
|
||||
xml配置目录下创建User表的mapper配置
|
||||
|
||||
```
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
@@ -213,6 +219,7 @@ mybatis.mapper-locations=classpath:mapper/*.xml
|
||||
```
|
||||
|
||||
### 对xml方式进行调用
|
||||
|
||||
```
|
||||
@Slf4j
|
||||
@RunWith(SpringRunner.class)
|
||||
@@ -234,11 +241,19 @@ public class Chapter36ApplicationTests {
|
||||
}
|
||||
```
|
||||
|
||||
## 5 整合 MyBatis-Plus 完成CRUD
|
||||
## 4 MyBatis-Plus
|
||||
|
||||
### 什么是MyBatis-Plus
|
||||
|
||||
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
|
||||
mybatis plus 官网
|
||||
建议安装 MybatisX 插件
|
||||
建议安装 MybatisX 插件
|
||||
|
||||
* 通用Mapper能力
|
||||
* 增强单表查询能力
|
||||
* 多种主键策略,支持UUID和雪花算法
|
||||
* 基础代码生成器
|
||||
* 乐观锁
|
||||
|
||||
### 引入
|
||||
|
||||
@@ -249,7 +264,9 @@ mybatis plus 官网
|
||||
<version>3.4.1</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
### 自动配置
|
||||
|
||||
● MybatisPlusAutoConfiguration 配置类,MybatisPlusProperties 配置项绑定。mybatis-plus:xxx 就是对mybatis-plus的定制
|
||||
● SqlSessionFactory 自动配置好。底层是容器中默认的数据源
|
||||
● mapperLocations 自动配置好的。有默认值。classpath*:/mapper/**/*.xml;任意包的类路径下的所有mapper文件夹下任意路径下的所有xml都是sql映射文件。 建议以后sql映射文件,放在 mapper下
|
||||
@@ -261,55 +278,168 @@ mybatis plus 官网
|
||||
优点:
|
||||
● 只需要我们的Mapper继承 BaseMapper 就可以拥有crud能力
|
||||
|
||||
### 进阶操作
|
||||
|
||||
1. 设置表明和自增主键
|
||||
2. 使用条件构造器
|
||||
1. `boolean condition`表示该条件**是否**加入最后生成的sql中
|
||||
2. 支持多种条件表达式拼接SQL语句。每种表达式有多种类型的接口
|
||||
|
||||
```
|
||||
AbstractWrapper
|
||||
allEq
|
||||
eq
|
||||
ne
|
||||
gt
|
||||
ge
|
||||
lt
|
||||
le
|
||||
between
|
||||
notBetween
|
||||
like
|
||||
notLike
|
||||
likeLeft
|
||||
likeRight
|
||||
notLikeLeft
|
||||
notLikeRight
|
||||
isNull
|
||||
isNotNull
|
||||
in
|
||||
notIn
|
||||
inSql
|
||||
notInSql
|
||||
groupBy
|
||||
orderByAsc
|
||||
orderByDesc
|
||||
orderBy
|
||||
having
|
||||
func
|
||||
or
|
||||
and
|
||||
nested
|
||||
apply
|
||||
last
|
||||
exists
|
||||
notExists
|
||||
QueryWrapper
|
||||
select
|
||||
UpdateWrapper
|
||||
set
|
||||
setSql
|
||||
lambda
|
||||
```
|
||||
|
||||
|
||||
|
||||
### CRUD实例
|
||||
|
||||
### CRUD
|
||||
DAO层
|
||||
|
||||
```java
|
||||
@GetMapping("/user/delete/{id}")
|
||||
public String deleteUser(@PathVariable("id") Long id,
|
||||
@RequestParam(value = "pn",defaultValue = "1")Integer pn,
|
||||
RedirectAttributes ra){
|
||||
|
||||
public interface ArticleMapper extends BaseMapper<Article> {
|
||||
}
|
||||
|
||||
userService.removeById(id);
|
||||
|
||||
ra.addAttribute("pn",pn);
|
||||
return "redirect:/dynamic_table";
|
||||
public interface BaseMapper<T> extends Mapper<T> {
|
||||
int insert(T entity);
|
||||
|
||||
int deleteById(Serializable id);
|
||||
|
||||
int deleteById(T entity);
|
||||
|
||||
default int deleteByMap(Map<String, Object> columnMap) {
|
||||
return this.delete((Wrapper)Wrappers.query().allEq(columnMap));
|
||||
}
|
||||
|
||||
int delete(@Param("ew") Wrapper<T> queryWrapper);
|
||||
|
||||
@GetMapping("/dynamic_table")
|
||||
public String dynamic_table(@RequestParam(value="pn",defaultValue = "1") Integer pn,Model model){
|
||||
//表格内容的遍历
|
||||
// response.sendError
|
||||
// List<User> users = Arrays.asList(new User("zhangsan", "123456"),
|
||||
// new User("lisi", "123444"),
|
||||
// new User("haha", "aaaaa"),
|
||||
// new User("hehe ", "aaddd"));
|
||||
// model.addAttribute("users",users);
|
||||
//
|
||||
// if(users.size()>3){
|
||||
// throw new UserTooManyException();
|
||||
// }
|
||||
//从数据库中查出user表中的用户进行展示
|
||||
int deleteBatchIds(@Param("coll") Collection<?> idList);
|
||||
|
||||
//构造分页参数
|
||||
Page<User> page = new Page<>(pn, 2);
|
||||
//调用page进行分页
|
||||
Page<User> userPage = userService.page(page, null);
|
||||
int updateById(@Param("et") T entity);
|
||||
|
||||
int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
|
||||
|
||||
// userPage.getRecords()
|
||||
// userPage.getCurrent()
|
||||
// userPage.getPages()
|
||||
|
||||
|
||||
model.addAttribute("users",userPage);
|
||||
|
||||
return "table/dynamic_table";
|
||||
default int update(@Param("ew") Wrapper<T> updateWrapper) {
|
||||
return this.update((Object)null, updateWrapper);
|
||||
}
|
||||
|
||||
T selectById(Serializable id);
|
||||
|
||||
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
|
||||
|
||||
void selectBatchIds(@Param("coll") Collection<? extends Serializable> idList, ResultHandler<T> resultHandler);
|
||||
|
||||
default List<T> selectByMap(Map<String, Object> columnMap) {
|
||||
return this.selectList((Wrapper)Wrappers.query().allEq(columnMap));
|
||||
}
|
||||
|
||||
default void selectByMap(Map<String, Object> columnMap, ResultHandler<T> resultHandler) {
|
||||
this.selectList((Wrapper)Wrappers.query().allEq(columnMap), resultHandler);
|
||||
}
|
||||
|
||||
default T selectOne(@Param("ew") Wrapper<T> queryWrapper) {
|
||||
return this.selectOne(queryWrapper, true);
|
||||
}
|
||||
|
||||
default T selectOne(@Param("ew") Wrapper<T> queryWrapper, boolean throwEx) {
|
||||
List<T> list = this.selectList(queryWrapper);
|
||||
int size = list.size();
|
||||
if (size == 1) {
|
||||
return list.get(0);
|
||||
} else if (size > 1) {
|
||||
if (throwEx) {
|
||||
throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + size);
|
||||
} else {
|
||||
return list.get(0);
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
default boolean exists(Wrapper<T> queryWrapper) {
|
||||
Long count = this.selectCount(queryWrapper);
|
||||
return null != count && count > 0L;
|
||||
}
|
||||
|
||||
Long selectCount(@Param("ew") Wrapper<T> queryWrapper);
|
||||
|
||||
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
|
||||
|
||||
void selectList(@Param("ew") Wrapper<T> queryWrapper, ResultHandler<T> resultHandler);
|
||||
|
||||
List<T> selectList(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper);
|
||||
|
||||
void selectList(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper, ResultHandler<T> resultHandler);
|
||||
|
||||
List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);
|
||||
|
||||
void selectMaps(@Param("ew") Wrapper<T> queryWrapper, ResultHandler<Map<String, Object>> resultHandler);
|
||||
|
||||
List<Map<String, Object>> selectMaps(IPage<? extends Map<String, Object>> page, @Param("ew") Wrapper<T> queryWrapper);
|
||||
|
||||
void selectMaps(IPage<? extends Map<String, Object>> page, @Param("ew") Wrapper<T> queryWrapper, ResultHandler<Map<String, Object>> resultHandler);
|
||||
|
||||
<E> List<E> selectObjs(@Param("ew") Wrapper<T> queryWrapper);
|
||||
|
||||
<E> void selectObjs(@Param("ew") Wrapper<T> queryWrapper, ResultHandler<E> resultHandler);
|
||||
|
||||
default <P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper) {
|
||||
page.setRecords(this.selectList(page, queryWrapper));
|
||||
return page;
|
||||
}
|
||||
|
||||
default <P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param("ew") Wrapper<T> queryWrapper) {
|
||||
page.setRecords(this.selectMaps(page, queryWrapper));
|
||||
return page;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Service层
|
||||
|
||||
```java
|
||||
@Service
|
||||
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
|
||||
@@ -320,4 +450,240 @@ public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements Use
|
||||
public interface UserService extends IService<User> {
|
||||
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
#### 完整实例
|
||||
|
||||
```java
|
||||
package com.baomidou.mybatisplus.samples.crud;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.samples.crud.entity.User;
|
||||
import com.baomidou.mybatisplus.samples.crud.entity.User2;
|
||||
import com.baomidou.mybatisplus.samples.crud.mapper.User2Mapper;
|
||||
import com.baomidou.mybatisplus.samples.crud.mapper.UserMapper;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 内置 CRUD 演示
|
||||
* </p>
|
||||
*
|
||||
* @author hubin
|
||||
* @since 2018-08-11
|
||||
*/
|
||||
@SpringBootTest
|
||||
public class CrudTest {
|
||||
@Autowired
|
||||
private UserMapper mapper;
|
||||
@Autowired
|
||||
private User2Mapper user2Mapper;
|
||||
|
||||
@Test
|
||||
public void aInsert() {
|
||||
User user = new User();
|
||||
user.setName("小羊");
|
||||
user.setAge(3);
|
||||
user.setEmail("abc@mp.com");
|
||||
assertThat(mapper.insert(user)).isGreaterThan(0);
|
||||
// 成功直接拿回写的 ID
|
||||
assertThat(user.getId()).isNotNull();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void bDelete() {
|
||||
assertThat(mapper.deleteById(3L)).isGreaterThan(0);
|
||||
assertThat(mapper.delete(new QueryWrapper<User>()
|
||||
.lambda().eq(User::getName, "Sandy"))).isGreaterThan(0);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void cUpdate() {
|
||||
assertThat(mapper.updateById(new User().setId(1L).setEmail("ab@c.c"))).isGreaterThan(0);
|
||||
assertThat(
|
||||
mapper.update(
|
||||
new User().setName("mp"),
|
||||
Wrappers.<User>lambdaUpdate()
|
||||
.set(User::getAge, 3)
|
||||
.eq(User::getId, 2)
|
||||
)
|
||||
).isGreaterThan(0);
|
||||
User user = mapper.selectById(2);
|
||||
assertThat(user.getAge()).isEqualTo(3);
|
||||
assertThat(user.getName()).isEqualTo("mp");
|
||||
|
||||
mapper.update(
|
||||
null,
|
||||
Wrappers.<User>lambdaUpdate().set(User::getEmail, null).eq(User::getId, 2)
|
||||
);
|
||||
assertThat(mapper.selectById(1).getEmail()).isEqualTo("ab@c.c");
|
||||
user = mapper.selectById(2);
|
||||
assertThat(user.getEmail()).isNull();
|
||||
assertThat(user.getName()).isEqualTo("mp");
|
||||
|
||||
mapper.update(
|
||||
new User().setEmail("miemie@baomidou.com"),
|
||||
new QueryWrapper<User>()
|
||||
.lambda().eq(User::getId, 2)
|
||||
);
|
||||
user = mapper.selectById(2);
|
||||
assertThat(user.getEmail()).isEqualTo("miemie@baomidou.com");
|
||||
|
||||
mapper.update(
|
||||
new User().setEmail("miemie2@baomidou.com"),
|
||||
Wrappers.<User>lambdaUpdate()
|
||||
.set(User::getAge, null)
|
||||
.eq(User::getId, 2)
|
||||
);
|
||||
user = mapper.selectById(2);
|
||||
assertThat(user.getEmail()).isEqualTo("miemie2@baomidou.com");
|
||||
assertThat(user.getAge()).isNull();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void dSelect() {
|
||||
mapper.insert(
|
||||
new User().setId(10086L)
|
||||
.setName("miemie")
|
||||
.setEmail("miemie@baomidou.com")
|
||||
.setAge(3));
|
||||
assertThat(mapper.selectById(10086L).getEmail()).isEqualTo("miemie@baomidou.com");
|
||||
User user = mapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getId, 10086));
|
||||
assertThat(user.getName()).isEqualTo("miemie");
|
||||
assertThat(user.getAge()).isEqualTo(3);
|
||||
|
||||
mapper.selectList(Wrappers.<User>lambdaQuery().select(User::getId))
|
||||
.forEach(x -> {
|
||||
assertThat(x.getId()).isNotNull();
|
||||
assertThat(x.getEmail()).isNull();
|
||||
assertThat(x.getName()).isNull();
|
||||
assertThat(x.getAge()).isNull();
|
||||
});
|
||||
mapper.selectList(new QueryWrapper<User>().select("id", "name"))
|
||||
.forEach(x -> {
|
||||
assertThat(x.getId()).isNotNull();
|
||||
assertThat(x.getEmail()).isNull();
|
||||
assertThat(x.getName()).isNotNull();
|
||||
assertThat(x.getAge()).isNull();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void orderBy() {
|
||||
List<User> users = mapper.selectList(Wrappers.<User>query().orderByAsc("age"));
|
||||
assertThat(users).isNotEmpty();
|
||||
//多字段排序
|
||||
List<User> users2 = mapper.selectList(Wrappers.<User>query().orderByAsc("age", "name"));
|
||||
assertThat(users2).isNotEmpty();
|
||||
//先按age升序排列,age相同再按name降序排列
|
||||
List<User> users3 = mapper.selectList(Wrappers.<User>query().orderByAsc("age").orderByDesc("name"));
|
||||
assertThat(users3).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void selectMaps() {
|
||||
List<Map<String, Object>> mapList = mapper.selectMaps(Wrappers.<User>query().orderByAsc("age"));
|
||||
assertThat(mapList).isNotEmpty();
|
||||
assertThat(mapList.get(0)).isNotEmpty();
|
||||
System.out.println(mapList.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void selectMapsPage() {
|
||||
IPage<Map<String, Object>> page = mapper.selectMapsPage(new Page<>(1, 5), Wrappers.<User>query().orderByAsc("age"));
|
||||
assertThat(page).isNotNull();
|
||||
assertThat(page.getRecords()).isNotEmpty();
|
||||
assertThat(page.getRecords().get(0)).isNotEmpty();
|
||||
System.out.println(page.getRecords().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void orderByLambda() {
|
||||
List<User> users = mapper.selectList(Wrappers.<User>lambdaQuery().orderByAsc(User::getAge));
|
||||
assertThat(users).isNotEmpty();
|
||||
//多字段排序
|
||||
List<User> users2 = mapper.selectList(Wrappers.<User>lambdaQuery().orderByAsc(User::getAge, User::getName));
|
||||
assertThat(users2).isNotEmpty();
|
||||
//先按age升序排列,age相同再按name降序排列
|
||||
List<User> users3 = mapper.selectList(Wrappers.<User>lambdaQuery().orderByAsc(User::getAge).orderByDesc(User::getName));
|
||||
assertThat(users3).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectMaxId() {
|
||||
QueryWrapper<User> wrapper = new QueryWrapper<>();
|
||||
wrapper.select("max(id) as id");
|
||||
User user = mapper.selectOne(wrapper);
|
||||
System.out.println("maxId=" + user.getId());
|
||||
List<User> users = mapper.selectList(Wrappers.<User>lambdaQuery().orderByDesc(User::getId));
|
||||
Assertions.assertEquals(user.getId().longValue(), users.get(0).getId().longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGroup() {
|
||||
QueryWrapper<User> wrapper = new QueryWrapper<>();
|
||||
wrapper.select("age, count(*)")
|
||||
.groupBy("age");
|
||||
List<Map<String, Object>> maplist = mapper.selectMaps(wrapper);
|
||||
for (Map<String, Object> mp : maplist) {
|
||||
System.out.println(mp);
|
||||
}
|
||||
/**
|
||||
* lambdaQueryWrapper groupBy orderBy
|
||||
*/
|
||||
LambdaQueryWrapper<User> lambdaQueryWrapper = new QueryWrapper<User>().lambda()
|
||||
.select(User::getAge)
|
||||
.groupBy(User::getAge)
|
||||
.orderByAsc(User::getAge);
|
||||
for (User user : mapper.selectList(lambdaQueryWrapper)) {
|
||||
System.out.println(user);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTableFieldExistFalse() {
|
||||
QueryWrapper<User> wrapper = new QueryWrapper<>();
|
||||
wrapper.select("age, count(age) as count")
|
||||
.groupBy("age");
|
||||
List<User> list = mapper.selectList(wrapper);
|
||||
list.forEach(System.out::println);
|
||||
list.forEach(x -> {
|
||||
Assertions.assertNull(x.getId());
|
||||
Assertions.assertNotNull(x.getAge());
|
||||
Assertions.assertNotNull(x.getCount());
|
||||
});
|
||||
mapper.insert(
|
||||
new User().setId(10088L)
|
||||
.setName("miemie")
|
||||
.setEmail("miemie@baomidou.com")
|
||||
.setAge(3));
|
||||
User miemie = mapper.selectById(10088L);
|
||||
Assertions.assertNotNull(miemie);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSqlCondition() {
|
||||
Assertions.assertEquals(user2Mapper.selectList(Wrappers.<User2>query()
|
||||
.setEntity(new User2().setName("n"))).size(), 2);
|
||||
Assertions.assertEquals(user2Mapper.selectList(Wrappers.<User2>query().like("name", "J")).size(), 2);
|
||||
Assertions.assertEquals(user2Mapper.selectList(Wrappers.<User2>query().gt("age", 18)
|
||||
.setEntity(new User2().setName("J"))).size(), 1);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -19,12 +19,12 @@ Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统
|
||||
### 配置原理
|
||||
|
||||
自动配置:
|
||||
● RedisAutoConfiguration 自动配置类。RedisProperties 属性类 --> spring.redis.xxx是对redis的配置
|
||||
● 连接工厂是准备好的。LettuceConnectionConfiguration、JedisConnectionConfiguration
|
||||
● 自动注入了RedisTemplate<Object, Object> : xxxTemplate;
|
||||
● 自动注入了StringRedisTemplate;k:v都是String
|
||||
● key:value
|
||||
● 底层只要我们使用 StringRedisTemplate、RedisTemplate就可以操作redis
|
||||
* RedisAutoConfiguration 自动配置类。RedisProperties 属性类 --> spring.redis.xxx是对redis的配置
|
||||
* 连接工厂是准备好的。LettuceConnectionConfiguration、JedisConnectionConfiguration
|
||||
* 自动注入了RedisTemplate<Object, Object> : xxxTemplate;
|
||||
* 自动注入了StringRedisTemplate;k:v都是String
|
||||
* key:value
|
||||
* 底层只要我们使用 StringRedisTemplate、RedisTemplate就可以操作redis
|
||||
|
||||
### 操作
|
||||
|
||||
|
||||
@@ -308,4 +308,47 @@ ConfigurableApplicationContext context = new SpringApplicationBuilder(Applicatio
|
||||
.sources(ApplicationConfiguration.class) //可以多个Class
|
||||
.run();
|
||||
context.close(); //上下文关闭
|
||||
```
|
||||
```
|
||||
|
||||
## 5 spring.fatoriesSPI中的扩展点
|
||||
|
||||
在 Spring 框架中,spring.factories 文件是一个 SPI (Service Provider Interface) 的形式,它可以用于定义和加载多个框架扩展点。这些扩展点允许开发人员插入自定义逻辑或覆盖框架提供的默认行为。Spring Boot 使用 spring.factories 文件来支持各种类型的扩展和自定义。
|
||||
|
||||
spring.factories 文件中可以配置的一些主要扩展点包括:
|
||||
|
||||
自动配置 (EnableAutoConfiguration):
|
||||
通过在 spring.factories 中列出自动配置类,Spring Boot 可以在启动时自动应用这些配置。这些配置通常会基于类路径和其他环境条件来条件性地配置 Bean。
|
||||
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.MyAutoConfiguration
|
||||
应用程序事件监听器 (ApplicationListener):
|
||||
应用程序事件监听器可以监听和响应 Spring 应用程序上下文中的各种事件,如应用启动、停止和环境准备等。
|
||||
|
||||
org.springframework.context.ApplicationListener=com.example.MyApplicationListener
|
||||
失败分析 (FailureAnalyzer):
|
||||
当应用程序启动失败时,失败分析器可以提供特定的错误报告和解决建议。
|
||||
|
||||
org.springframework.boot.diagnostics.FailureAnalyzer=com.example.MyFailureAnalyzer
|
||||
模板引擎 (TemplateAvailabilityProviders):
|
||||
用于检测是否应该呈现模板以及哪种类型的模板可用。
|
||||
|
||||
org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=com.example.MyTemplateAvailabilityProvider
|
||||
环境后处理器 (EnvironmentPostProcessor):
|
||||
环境后处理器允许开发人员在应用程序上下文刷新之前对环境(配置属性)进行编程更改。
|
||||
|
||||
org.springframework.boot.env.EnvironmentPostProcessor=com.example.MyEnvironmentPostProcessor
|
||||
应用程序上下文初始化器 (ApplicationContextInitializer):
|
||||
在 ApplicationContext 实例化之前初始化 ApplicationContext 的回调接口,可以用来设置上下文的状态或添加自定义的逻辑。
|
||||
|
||||
org.springframework.context.ApplicationContextInitializer=com.example.MyApplicationContextInitializer
|
||||
命令行运行器 (CommandLineRunner) 和 应用程序运行器 (ApplicationRunner):
|
||||
它们允许在 SpringApplication 运行之后,执行一些额外的代码。
|
||||
|
||||
org.springframework.boot.CommandLineRunner=com.example.MyCommandLineRunner
|
||||
org.springframework.boot.ApplicationRunner=com.example.MyApplicationRunner
|
||||
管理端点 (Endpoint):
|
||||
自定义管理端点可以通过 Spring Boot Actuator 暴露。
|
||||
|
||||
org.springframework.boot.actuate.endpoint.Endpoint=com.example.MyCustomEndpoint
|
||||
使用 spring.factories 文件为框架扩展点提供实现有几个好处:它支持条件化配置、松耦合、易于维护,并且可以在不修改主应用程序代码的情况下增强框架功能。
|
||||
|
||||
为了使用这些扩展点,开发人员需要在项目的 resources/META-INF/spring.factories 文件中指定他们的实现。然后,当应用程序启动时,Spring Boot 将自动发现并注册这些实现。
|
||||
Reference in New Issue
Block a user