mirror of
https://github.com/Estom/notes.git
synced 2026-04-03 19:07:41 +08:00
mybatis
This commit is contained in:
218
Springboot/10Springboot-MyBatis.md
Normal file
218
Springboot/10Springboot-MyBatis.md
Normal file
@@ -0,0 +1,218 @@
|
||||
> 对象关系映射模型Hibernate。用来实现非常轻量级的对象的封装。将对象与数据库建立映射关系。实现增删查改。
|
||||
> MyBatis与Hibernate非常相似。对象关系映射模型ORG。java对象与关系数据库映射的模型。
|
||||
|
||||
## 1 配置MyBatis
|
||||
|
||||
### 在pom.xml中添加MyBatis依赖
|
||||
|
||||
```
|
||||
<dependency>
|
||||
<groupId>org.mybatis.spring.boot</groupId>
|
||||
<artifactId>mybatis-spring-boot-starter</artifactId>
|
||||
<version>2.1.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
### 在application.properties中配置mysql的链接配置
|
||||
|
||||
```
|
||||
spring.datasource.url=jdbc:mysql://localhost:3306/test
|
||||
spring.datasource.username=root
|
||||
spring.datasource.password=
|
||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
```
|
||||
|
||||
### 创建关系数据表
|
||||
|
||||
```
|
||||
CREATE TABLE `User` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`name` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL,
|
||||
`age` int DEFAULT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
|
||||
```
|
||||
|
||||
### 创建数据表的java对象
|
||||
|
||||
```
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class User {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
private Integer age;
|
||||
|
||||
public User(String name, Integer age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 创建数据表的操作接口
|
||||
|
||||
```
|
||||
@Mapper
|
||||
public interface UserMapper {
|
||||
|
||||
@Select("SELECT * FROM USER WHERE NAME = #{name}")
|
||||
User findByName(@Param("name") String name);
|
||||
|
||||
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
|
||||
int insert(@Param("name") String name, @Param("age") Integer age);
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
## 2 MyBatis参数传递
|
||||
|
||||
### 使用@Param参数传递
|
||||
|
||||
```
|
||||
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
|
||||
int insert(@Param("name") String name, @Param("age") Integer age);
|
||||
```
|
||||
|
||||
### 使用map 传递参数
|
||||
|
||||
```
|
||||
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
|
||||
int insertByMap(Map<String, Object> map);
|
||||
//调用
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("name", "CCC");
|
||||
map.put("age", 40);
|
||||
userMapper.insertByMap(map);
|
||||
```
|
||||
|
||||
### 使用普通java对象
|
||||
```
|
||||
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
|
||||
int insertByUser(User user);
|
||||
```
|
||||
## 3 增删查改操作
|
||||
|
||||
```
|
||||
public interface UserMapper {
|
||||
|
||||
@Select("SELECT * FROM user WHERE name = #{name}")
|
||||
User findByName(@Param("name") String name);
|
||||
|
||||
@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
|
||||
int insert(@Param("name") String name, @Param("age") Integer age);
|
||||
|
||||
@Update("UPDATE user SET age=#{age} WHERE name=#{name}")
|
||||
void update(User user);
|
||||
|
||||
@Delete("DELETE FROM user WHERE id =#{id}")
|
||||
void delete(Long id);
|
||||
}
|
||||
```
|
||||
对增删查改的调用
|
||||
```
|
||||
@Transactional
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class ApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private UserMapper userMapper;
|
||||
|
||||
@Test
|
||||
@Rollback
|
||||
public void testUserMapper() throws Exception {
|
||||
// insert一条数据,并select出来验证
|
||||
userMapper.insert("AAA", 20);
|
||||
User u = userMapper.findByName("AAA");
|
||||
Assert.assertEquals(20, u.getAge().intValue());
|
||||
// update一条数据,并select出来验证
|
||||
u.setAge(30);
|
||||
userMapper.update(u);
|
||||
u = userMapper.findByName("AAA");
|
||||
Assert.assertEquals(30, u.getAge().intValue());
|
||||
// 删除这条数据,并select验证
|
||||
userMapper.delete(u.getId());
|
||||
u = userMapper.findByName("AAA");
|
||||
Assert.assertEquals(null, u);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 4 使用MyBatis的XML方式
|
||||
|
||||
### 在应用主类中增加mapper的扫描包配置:
|
||||
```
|
||||
@MapperScan("com.didispace.chapter36.mapper")
|
||||
@SpringBootApplication
|
||||
public class Chapter36Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Chapter36Application.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### Mapper包下创建User表
|
||||
```
|
||||
public interface UserMapper {
|
||||
|
||||
User findByName(@Param("name") String name);
|
||||
|
||||
int insert(@Param("name") String name, @Param("age") Integer age);
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### 在配置文件中通过mybatis.mapper-locations参数指定xml配置的位置
|
||||
|
||||
```
|
||||
mybatis.mapper-locations=classpath:mapper/*.xml
|
||||
```
|
||||
### xml配置目录下创建User表的mapper配置
|
||||
|
||||
```
|
||||
<?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.didispace.chapter36.mapper.UserMapper">
|
||||
<select id="findByName" resultType="com.didispace.chapter36.entity.User">
|
||||
SELECT * FROM USER WHERE NAME = #{name}
|
||||
</select>
|
||||
|
||||
<insert id="insert">
|
||||
INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})
|
||||
</insert>
|
||||
</mapper>
|
||||
```
|
||||
|
||||
### 对xml方式进行调用
|
||||
```
|
||||
@Slf4j
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@Transactional
|
||||
public class Chapter36ApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private UserMapper userMapper;
|
||||
|
||||
@Test
|
||||
@Rollback
|
||||
public void test() throws Exception {
|
||||
userMapper.insert("AAA", 20);
|
||||
User u = userMapper.findByName("AAA");
|
||||
Assert.assertEquals(20, u.getAge().intValue());
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
83
Springboot/1简介.md
Normal file
83
Springboot/1简介.md
Normal file
@@ -0,0 +1,83 @@
|
||||
## 1 简介
|
||||
|
||||
Spring Boot 是基于 Spring 框架基础上推出的一个全新的框架, 旨在让开发者可以轻松地创建一个可独立运行的,生产级别的应用程序。利用控制反转的核心特性,并通过依赖注入实现控制反转来实现管理对象生命周期容器化,利用面向切面编程进行声明式的事务管理,整合多种持久化技术管理数据访问,提供大量优秀的Web框架方便开发等等。
|
||||
|
||||
### Springboot的优势
|
||||
|
||||
1. 能够轻松、方便地创建一个 Spring 应用;
|
||||
2. 直接使用内嵌的 Tomcat, Jetty, Undertow 容器(无需再手动安装容器,通过部署 WAR 包的方式);
|
||||
3. 内部自动管理各种 Jar 包的版本依赖关系,再也不用为版本冲突而烦恼啦;
|
||||
4. 自动化配置 Spring 相关功能,以及第三方库;
|
||||
5. 提供诸如指标,健康检查, 外部化配置等功能;
|
||||
6. "零配置",再也不需要手写地狱般的 XML 配置了;
|
||||
|
||||
|
||||
## 2 相关特性
|
||||
|
||||
### REST风格
|
||||
|
||||
### 控制反转
|
||||
|
||||
### 面向切面
|
||||
|
||||
|
||||
## 3 工程结构
|
||||
|
||||
### 推荐工程结构
|
||||
```
|
||||
com
|
||||
+- example
|
||||
+- myproject
|
||||
+- Application.java
|
||||
|
|
||||
+- domain
|
||||
| +- Customer.java
|
||||
| +- CustomerRepository.java
|
||||
|
|
||||
+- service
|
||||
| +- CustomerService.java
|
||||
|
|
||||
+- web
|
||||
| +- CustomerController.java
|
||||
|
|
||||
```
|
||||
* root package:com.example.myproject,所有的类和其他package都在root package之下。
|
||||
* 应用主类:Application.java,该类直接位于root package下。通常我们会在应用主类中做一些框架配置扫描等配置,我们放在root package下可以帮助程序减少手工配置来加载到我们希望被Spring加载的内容
|
||||
* com.example.myproject.domain包:用于定义实体映射关系与数据访问相关的接口和实现
|
||||
* com.example.myproject.service包:用于编写业务逻辑相关的接口与实现
|
||||
* com.example.myproject.web:用于编写Web层相关的实现,比如:Spring MVC的Controller等
|
||||
|
||||
> Spring Boot的应用主类会自动扫描root package以及所有子包下的所有类来进行初始化。
|
||||
|
||||
|
||||
### 非典型结构下的初始化
|
||||
|
||||
1. 使用@ComponentScan注解指定具体的加载包
|
||||
|
||||
```
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages="com.example")
|
||||
public class Bootstrap {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Bootstrap.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
2. 使用@Bean注解来初始化。在主类中进行初始化。
|
||||
```
|
||||
@SpringBootApplication
|
||||
public class Bootstrap {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Bootstrap.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CustomerController customerController() {
|
||||
return new CustomerController();
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
240
Springboot/2配置.md
Normal file
240
Springboot/2配置.md
Normal file
@@ -0,0 +1,240 @@
|
||||
## 1 配置基础
|
||||
|
||||
### 默认配置文件
|
||||
用于配置容器端口名、数据库链接信息、日志级别。pom是项目编程的配置,properties是软件部署的配置。
|
||||
```
|
||||
src/main/resources/application.properties
|
||||
```
|
||||
|
||||
### yaml配置文件实例
|
||||
```
|
||||
environments:
|
||||
dev:
|
||||
url: http://dev.bar.com
|
||||
name: Developer Setup
|
||||
prod:
|
||||
url: http://foo.bar.com
|
||||
name: My Cool App
|
||||
```
|
||||
|
||||
### 等价的properties配置文件
|
||||
```
|
||||
environments.dev.url=http://dev.bar.com
|
||||
environments.dev.name=Developer Setup
|
||||
environments.prod.url=http://foo.bar.com
|
||||
environments.prod.name=My Cool App
|
||||
```
|
||||
|
||||
### yaml的自定义参数
|
||||
* 定义自定义的参数
|
||||
```
|
||||
book.name=SpringCloudInAction
|
||||
book.author=ZhaiYongchao
|
||||
```
|
||||
* 通过占位符的方式加载自定义的参数
|
||||
|
||||
```
|
||||
@Component
|
||||
public class Book {
|
||||
|
||||
@Value("${book.name}")
|
||||
private String name;
|
||||
@Value("${book.author}")
|
||||
private String author;
|
||||
|
||||
// 省略getter和setter
|
||||
}
|
||||
```
|
||||
|
||||
* 通过SpEL表达式加载自定义参数
|
||||
|
||||
'''
|
||||
#{...}
|
||||
'''
|
||||
|
||||
### 使用随机数配置
|
||||
${random}的配置方式主要有一下几种,读者可作为参考使用。
|
||||
|
||||
```
|
||||
# 随机字符串
|
||||
com.didispace.blog.value=${random.value}
|
||||
# 随机int
|
||||
com.didispace.blog.number=${random.int}
|
||||
# 随机long
|
||||
com.didispace.blog.bignumber=${random.long}
|
||||
# 10以内的随机数
|
||||
com.didispace.blog.test1=${random.int(10)}
|
||||
# 10-20的随机数
|
||||
com.didispace.blog.test2=${random.int[10,20]}
|
||||
```
|
||||
|
||||
|
||||
### 通过命令行配置
|
||||
在启动java应用是,添加配置参数
|
||||
```
|
||||
java -jar xxx.jar --server.port=8888
|
||||
```
|
||||
|
||||
|
||||
## 2 多环境配置
|
||||
|
||||
### 配置方法
|
||||
对于多环境的配置,各种项目构建工具或是框架的基本思路是一致的,通过配置多份不同环境的配置文件,再通过打包命令指定需要打包的内容之后进行区分打包。
|
||||
|
||||
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:
|
||||
|
||||
* application-dev.properties:开发环境
|
||||
* application-test.properties:测试环境
|
||||
* application-prod.properties:生产环境
|
||||
|
||||
### 配置加载顺序
|
||||
|
||||
1. 命令行中传入的参数。
|
||||
1. SPRING_APPLICATION_JSON中的属性。SPRING_APPLICATION_JSON是以JSON格式配置在系统环境变量中的内容。
|
||||
1. java:comp/env中的JNDI属性。
|
||||
1. Java的系统属性,可以通过System.getProperties()获得的内容。
|
||||
1. 操作系统的环境变量
|
||||
1. 通过random.*配置的随机属性
|
||||
1. 位于当前应用jar包之外,针对不同{profile}环境的配置文件内容,例如:application-{profile}.properties或是YAML定义的配置文件
|
||||
1. 位于当前应用jar包之内,针对不同{profile}环境的配置文件内容,例如:application-{profile}.properties或是YAML定义的配置文件
|
||||
1. 位于当前应用jar包之外的application.properties和YAML配置内容
|
||||
1. 位于当前应用jar包之内的application.properties和YAML配置内容
|
||||
1. 在@Configuration注解修改的类中,通过@PropertySource注解定义的属性
|
||||
1. 应用默认属性,使用SpringApplication.setDefaultProperties定义的内容1.
|
||||
|
||||
## 3 配置文件属性绑定
|
||||
|
||||
### Spring Boot 2.0 新特性
|
||||
* 移除特殊字符
|
||||
* 全小写
|
||||
|
||||
### 列表类型
|
||||
> 必须使用连续下标索引进行配置。
|
||||
* properties中使用[]在定位列表类型
|
||||
```
|
||||
pring.my-example.url[0]=http://example.com
|
||||
spring.my-example.url[1]=http://spring.io
|
||||
```
|
||||
* properties中使用,分割列表类型。
|
||||
|
||||
```
|
||||
pring.my-example.url[0]=http://example.com
|
||||
spring.my-example.url[1]=http://spring.io
|
||||
```
|
||||
|
||||
* yaml中使用列表
|
||||
|
||||
```
|
||||
spring:
|
||||
my-example:
|
||||
url:
|
||||
- http://example.com
|
||||
- http://spring.io
|
||||
|
||||
```
|
||||
* yaml文件中使用,分割列表
|
||||
```
|
||||
spring:
|
||||
my-example:
|
||||
url: http://example.com, http://spring.io
|
||||
```
|
||||
### Map类型
|
||||
|
||||
Map类型在properties和yaml中的标准配置方式如下:
|
||||
|
||||
* properties格式:
|
||||
|
||||
```
|
||||
spring.my-example.foo=bar
|
||||
spring.my-example.hello=world
|
||||
```
|
||||
* yaml格式:
|
||||
```
|
||||
spring:
|
||||
my-example:
|
||||
foo: bar
|
||||
hello: world
|
||||
```
|
||||
|
||||
## 4 环境属性绑定
|
||||
### 简单类型
|
||||
在环境变量中通过小写转换与.替换_来映射配置文件中的内容,比如:环境变量SPRING_JPA_DATABASEPLATFORM=mysql的配置会产生与在配置文件中设置spring.jpa.databaseplatform=mysql一样的效果。
|
||||
|
||||
### List类型
|
||||
由于环境变量中无法使用[和]符号,所以使用_来替代。任何由下划线包围的数字都会被认为是[]的数组形式。
|
||||
```
|
||||
MY_FOO_1_ = my.foo[1]
|
||||
MY_FOO_1_BAR = my.foo[1].bar
|
||||
MY_FOO_1_2_ = my.foo[1][2]
|
||||
```
|
||||
|
||||
## 5 系统属性绑定
|
||||
|
||||
### 简单类型
|
||||
|
||||
系统属性与文件配置中的类似,都以移除特殊字符并转化小写后实现绑定
|
||||
|
||||
### list类型
|
||||
|
||||
系统属性的绑定也与文件属性的绑定类似,通过[]来标示,比如:
|
||||
|
||||
```
|
||||
-D"spring.my-example.url[0]=http://example.com"
|
||||
-D"spring.my-example.url[1]=http://spring.io"
|
||||
```
|
||||
|
||||
同样的,他也支持逗号分割的方式,比如:
|
||||
```
|
||||
-Dspring.my-example.url=http://example.com,http://spring.io
|
||||
```
|
||||
|
||||
## 6 属性读取
|
||||
|
||||
在Spring应用程序的environment中读取属性的时候,每个属性的唯一名称符合如下规则:
|
||||
|
||||
* 通过.分离各个元素
|
||||
* 最后一个.将前缀与属性名称分开
|
||||
* 必须是字母(a-z)和数字(0-9)
|
||||
* 必须是小写字母
|
||||
* 用连字符-来分隔单词
|
||||
* 唯一允许的其他字符是[和],用于List的索引
|
||||
* 不能以数字开头
|
||||
|
||||
```
|
||||
this.environment.containsProperty("spring.jpa.database-platform")
|
||||
```
|
||||
|
||||
## 7 新的绑定API
|
||||
|
||||
简单类型
|
||||
|
||||
假设在propertes配置中有这样一个配置:
|
||||
```
|
||||
com.didispace.foo=bar
|
||||
```
|
||||
我们为它创建对应的配置类:
|
||||
```
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "com.didispace")
|
||||
public class FooProperties {
|
||||
|
||||
private String foo;
|
||||
|
||||
}
|
||||
```
|
||||
接下来,通过最新的Binder就可以这样来拿配置信息了:
|
||||
```
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
ApplicationContext context = SpringApplication.run(Application.class, args);
|
||||
|
||||
Binder binder = Binder.get(context.getEnvironment());
|
||||
|
||||
// 绑定简单配置
|
||||
FooProperties foo = binder.bind("com.didispace", Bindable.of(FooProperties.class)).get();
|
||||
System.out.println(foo.getFoo());
|
||||
}
|
||||
}
|
||||
```
|
||||
75
Springboot/3Restful API.md
Normal file
75
Springboot/3Restful API.md
Normal file
@@ -0,0 +1,75 @@
|
||||
```
|
||||
@RestController
|
||||
@RequestMapping(value = "/users") // 通过这里配置使下面的映射都在/users下
|
||||
public class UserController {
|
||||
|
||||
// 创建线程安全的Map,模拟users信息的存储
|
||||
static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
|
||||
|
||||
/**
|
||||
* 处理"/users/"的GET请求,用来获取用户列表
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/")
|
||||
public List<User> getUserList() {
|
||||
// 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
|
||||
List<User> r = new ArrayList<User>(users.values());
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理"/users/"的POST请求,用来创建User
|
||||
*
|
||||
* @param user
|
||||
* @return
|
||||
*/
|
||||
@PostMapping("/")
|
||||
public String postUser(@RequestBody User user) {
|
||||
// @RequestBody注解用来绑定通过http请求中application/json类型上传的数据
|
||||
users.put(user.getId(), user);
|
||||
return "success";
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
|
||||
*
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
public User getUser(@PathVariable Long id) {
|
||||
// url中的id可通过@PathVariable绑定到函数的参数中
|
||||
return users.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理"/users/{id}"的PUT请求,用来更新User信息
|
||||
*
|
||||
* @param id
|
||||
* @param user
|
||||
* @return
|
||||
*/
|
||||
@PutMapping("/{id}")
|
||||
public String putUser(@PathVariable Long id, @RequestBody User user) {
|
||||
User u = users.get(id);
|
||||
u.setName(user.getName());
|
||||
u.setAge(user.getAge());
|
||||
users.put(id, u);
|
||||
return "success";
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理"/users/{id}"的DELETE请求,用来删除User
|
||||
*
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
@DeleteMapping("/{id}")
|
||||
public String deleteUser(@PathVariable Long id) {
|
||||
users.remove(id);
|
||||
return "success";
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
15
Springboot/4注解详解.md
Normal file
15
Springboot/4注解详解.md
Normal file
@@ -0,0 +1,15 @@
|
||||
## Springboot注解
|
||||
|
||||
|
||||
@Controller:修饰class,用来创建处理http请求的对象
|
||||
@RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合
|
||||
@ResponseBody,默认返回json格式
|
||||
@RequestMapping:配置url映射。现在更多的也会直接用以Http Method直接关联的映射注解来定义,比如:GetMapping、PostMapping、DeleteMapping、PutMapping等
|
||||
|
||||
|
||||
## 其他注解
|
||||
|
||||
@Data注解可以实现在编译器自动添加set和get函数的效果。该注解是lombok提供的
|
||||
@NoArgsConstructor创建无参数构造函数。
|
||||
|
||||
|
||||
39
Springboot/5Swagger2.md
Normal file
39
Springboot/5Swagger2.md
Normal file
@@ -0,0 +1,39 @@
|
||||
## swagger2使用
|
||||
|
||||
### pom.xml添加依赖
|
||||
|
||||
```
|
||||
<dependency>
|
||||
<groupId>com.spring4all</groupId>
|
||||
<artifactId>swagger-spring-boot-starter</artifactId>
|
||||
<version>1.9.0.RELEASE</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
### 应用主类中添加@EnableSwagger2Doc注解
|
||||
|
||||
```
|
||||
@EnableSwagger2Doc
|
||||
@SpringBootApplication
|
||||
public class Chapter22Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Chapter22Application.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### application.properties中配置文档相关内容,比如
|
||||
|
||||
swagger.title=spring-boot-starter-swagger
|
||||
swagger.description=Starter for swagger 2.x
|
||||
swagger.version=1.4.0.RELEASE
|
||||
swagger.license=Apache License, Version 2.0
|
||||
swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html
|
||||
swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger
|
||||
swagger.contact.name=didi
|
||||
swagger.contact.url=http://blog.didispace.com
|
||||
swagger.contact.email=dyc87112@qq.com
|
||||
swagger.base-package=com.didispace
|
||||
swagger.base-path=/**
|
||||
206
Springboot/6Springboot-jdbc.md
Normal file
206
Springboot/6Springboot-jdbc.md
Normal file
@@ -0,0 +1,206 @@
|
||||
## 1 jdbc配置
|
||||
|
||||
> 数据库与数据源不是同一个东西。。。
|
||||
|
||||
|
||||
### 数据源配置
|
||||
pom.xml
|
||||
|
||||
```
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
### 嵌入式数据库支持
|
||||
嵌入式数据库支持:H2、HSQL、Derby。不需要任何配置,被集成到springboot的jar包当中。
|
||||
```
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
### 连接mysql数据库
|
||||
|
||||
* 引入mysql依赖包
|
||||
|
||||
```
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
* 配置数据源信息
|
||||
```
|
||||
spring.datasource.url=jdbc:mysql://localhost:3306/test
|
||||
spring.datasource.username=dbuser
|
||||
spring.datasource.password=dbpass
|
||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver//定义了数据引擎
|
||||
```
|
||||
|
||||
### 连接JNDI数据源
|
||||
|
||||
JNDI,避免了程序与数据库之间的紧耦合,是指更容易配置和部署。
|
||||
|
||||
JNDI不需要用户使用java代码与数据库建立连接,而是将连接交给应用服务器进行管理。java负责与应用服务器上的JNDI通信。
|
||||
```
|
||||
spring.datasource.jndi-name=java:jboss/datasources/customers
|
||||
```
|
||||
|
||||
## 2 使用jdbcTemplate操作数据库
|
||||
|
||||
### 准备数据库
|
||||
```
|
||||
CREATE TABLE `User` (
|
||||
`name` varchar(100) COLLATE utf8mb4_general_ci NOT NULL,
|
||||
`age` int NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
|
||||
```
|
||||
|
||||
### 编写领域对象(并不是MVC的一部分。数据层,实现数据访问)
|
||||
|
||||
```
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
public class User {
|
||||
|
||||
private String name;
|
||||
private Integer age;
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### 编写数据访问对象(并非MVC的一部分。服务层,实现业务逻辑)
|
||||
* 定义包含插入、删除、查询的抽象接口UserService
|
||||
```
|
||||
定义包含有插入、删除、查询的抽象接口UserService
|
||||
public interface UserService {
|
||||
|
||||
/**
|
||||
* 新增一个用户
|
||||
*
|
||||
* @param name
|
||||
* @param age
|
||||
*/
|
||||
int create(String name, Integer age);
|
||||
|
||||
/**
|
||||
* 根据name查询用户
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
List<User> getByName(String name);
|
||||
|
||||
/**
|
||||
* 根据name删除用户
|
||||
*
|
||||
* @param name
|
||||
*/
|
||||
int deleteByName(String name);
|
||||
|
||||
/**
|
||||
* 获取用户总量
|
||||
*/
|
||||
int getAllUsers();
|
||||
|
||||
/**
|
||||
* 删除所有用户
|
||||
*/
|
||||
int deleteAllUsers();
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
* 通过jdbcTemplate实现Userservice中定义的操作。
|
||||
|
||||
```
|
||||
@Service
|
||||
public class UserServiceImpl implements UserService {
|
||||
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
UserServiceImpl(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int create(String name, Integer age) {
|
||||
return jdbcTemplate.update("insert into USER(NAME, AGE) values(?, ?)", name, age);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<User> getByName(String name) {
|
||||
List<User> users = jdbcTemplate.query("select NAME, AGE from USER where NAME = ?", (resultSet, i) -> {
|
||||
User user = new User();
|
||||
user.setName(resultSet.getString("NAME"));
|
||||
user.setAge(resultSet.getInt("AGE"));
|
||||
return user;
|
||||
}, name);
|
||||
return users;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteByName(String name) {
|
||||
return jdbcTemplate.update("delete from USER where NAME = ?", name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getAllUsers() {
|
||||
return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int deleteAllUsers() {
|
||||
return jdbcTemplate.update("delete from USER");
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### 编写单元测试用例
|
||||
创建对UserService的单元测试用例,通过创建、删除和查询来验证数据库操作的正确性。
|
||||
```
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class Chapter31ApplicationTests {
|
||||
|
||||
@Autowired
|
||||
private UserService userSerivce;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
// 准备,清空user表
|
||||
userSerivce.deleteAllUsers();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test() throws Exception {
|
||||
// 插入5个用户
|
||||
userSerivce.create("Tom", 10);
|
||||
userSerivce.create("Mike", 11);
|
||||
userSerivce.create("Didispace", 30);
|
||||
userSerivce.create("Oscar", 21);
|
||||
userSerivce.create("Linda", 17);
|
||||
|
||||
// 查询名为Oscar的用户,判断年龄是否匹配
|
||||
List<User> userList = userSerivce.getByName("Oscar");
|
||||
Assert.assertEquals(21, userList.get(0).getAge().intValue());
|
||||
|
||||
// 查数据库,应该有5个用户
|
||||
Assert.assertEquals(5, userSerivce.getAllUsers());
|
||||
|
||||
// 删除两个用户
|
||||
userSerivce.deleteByName("Tom");
|
||||
userSerivce.deleteByName("Mike");
|
||||
|
||||
// 查数据库,应该有5个用户
|
||||
Assert.assertEquals(3, userSerivce.getAllUsers());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
47
Springboot/7Springboot-Hikari数据源.md
Normal file
47
Springboot/7Springboot-Hikari数据源.md
Normal file
@@ -0,0 +1,47 @@
|
||||
## 1 基本概念
|
||||
|
||||
### JDBC
|
||||
|
||||
java数据库链接,java database connectivity。java语言用来规范客户访问数据库的应用程序接口。提供了查询、更新数据库的方法。java.sql与javax.sql主要包括以下类:
|
||||
|
||||
* DriverManager:负责加载不同的驱动程序Driver,返回相应的数据库连接Connection。
|
||||
* Driver:对应数据库的驱动程序。
|
||||
* Connection:数据库连接,负责与数据库进行通信。可以产生SQL的statement.
|
||||
* Statement:用来执行SQL查询和更新。
|
||||
* CallableStatement:用以调用数据库中的存储过程。
|
||||
* SQLException:代表数据库联机额的建立和关闭和SQL语句中发生的例情况。
|
||||
|
||||
### 数据源
|
||||
|
||||
1. 封装关于数据库访问的各种参数,实现统一管理。
|
||||
2. 通过数据库的连接池管理,节省开销并提高效率。
|
||||
|
||||
> 简单理解,就是在用户程序与数据库之间,建立新的缓冲地带,用来对用户的请求进行优化,对数据库的访问进行整合。
|
||||
|
||||
常见的数据源:DBCP、C3P0、Druid、HikariCP。
|
||||
|
||||
|
||||
## 2 HikariCP默认数据源配置
|
||||
|
||||
### 通用配置
|
||||
|
||||
以spring.datasource.*的形式存在,包括数据库连接地址、用户名、密码。
|
||||
```
|
||||
spring.datasource.url=jdbc:mysql://localhost:3306/test
|
||||
spring.datasource.username=root
|
||||
spring.datasource.password=123456
|
||||
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
|
||||
```
|
||||
|
||||
### 数据源连接配置
|
||||
|
||||
以spring.datasource.<数据源名称>.*的形式存在,
|
||||
```
|
||||
spring.datasource.hikari.minimum-idle=10//最小空闲连接
|
||||
spring.datasource.hikari.maximum-pool-size=20//最大连接数
|
||||
spring.datasource.hikari.idle-timeout=500000//控线连接超时时间
|
||||
spring.datasource.hikari.max-lifetime=540000//最大存活时间
|
||||
spring.datasource.hikari.connection-timeout=60000//连接超时时间
|
||||
spring.datasource.hikari.connection-test-query=SELECT 1//用于测试连接是否可用的查询语句
|
||||
```
|
||||
|
||||
61
Springboot/8Springboot-druid数据源.md
Normal file
61
Springboot/8Springboot-druid数据源.md
Normal file
@@ -0,0 +1,61 @@
|
||||
## 1 基本配置
|
||||
|
||||
### pom.xml配置druid依赖
|
||||
|
||||
```
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid-spring-boot-starter</artifactId>
|
||||
<version>1.1.21</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
### application.properties配置数据库连接信息
|
||||
|
||||
以spring.datasource.druid作为前缀
|
||||
```
|
||||
spring.datasource.druid.url=jdbc:mysql://localhost:3306/test
|
||||
spring.datasource.druid.username=root
|
||||
spring.datasource.druid.password=
|
||||
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
```
|
||||
|
||||
### 配置druid连接池
|
||||
> 具体的信息可以自己查询相关的内容。
|
||||
```
|
||||
spring.datasource.druid.initialSize=10
|
||||
spring.datasource.druid.maxActive=20
|
||||
spring.datasource.druid.maxWait=60000
|
||||
spring.datasource.druid.minIdle=1
|
||||
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
|
||||
spring.datasource.druid.minEvictableIdleTimeMillis=300000
|
||||
spring.datasource.druid.testWhileIdle=true
|
||||
spring.datasource.druid.testOnBorrow=true
|
||||
spring.datasource.druid.testOnReturn=false
|
||||
spring.datasource.druid.poolPreparedStatements=true
|
||||
spring.datasource.druid.maxOpenPreparedStatements=20
|
||||
spring.datasource.druid.validationQuery=SELECT 1
|
||||
spring.datasource.druid.validation-query-timeout=500
|
||||
spring.datasource.druid.filters=stat
|
||||
```
|
||||
|
||||
### 配置druid监控
|
||||
|
||||
* 在pom.xml中增加依赖
|
||||
|
||||
```
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
* 在application.properties中添加druid监控配置
|
||||
|
||||
```
|
||||
spring.datasource.druid.stat-view-servlet.enabled=true
|
||||
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
|
||||
spring.datasource.druid.stat-view-servlet.reset-enable=true
|
||||
spring.datasource.druid.stat-view-servlet.login-username=admin
|
||||
spring.datasource.druid.stat-view-servlet.login-password=admin
|
||||
```
|
||||
0
Springboot/9Springboot-Hibernate.md
Normal file
0
Springboot/9Springboot-Hibernate.md
Normal file
@@ -1,2 +0,0 @@
|
||||
利用控制反转的核心特性,并通过依赖注入实现控制反转来实现管理对象生命周期容器化,利用面向切面编程进行声明式的事务管理,整合多种持久化技术管理数据访问,提供大量优秀的Web框架方便开发等等。
|
||||
|
||||
Reference in New Issue
Block a user