SpringBoot-02-操作資料庫
阿新 • • 發佈:2020-12-21
4 SpringBoot操作資料庫
4.1 SpringData
什麼是SpringData
- SpringData是Spring全家桶中專門用於處理資料訪問層的元件了,它使用Spring的方式對所有SQL和NoSQL資料庫進行統一處理
- 在所有Spring專案的底層,都統一使用SpringData處理各種資料庫
4.2 整合JDBC
匯入對應的依賴
<dependencies> <!--JDBC--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--MySQL驅動--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies>
配置SpringBoot
-
配置檔案
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 url: jdbc:mysql://localhost:3306/springboot?serverTimezone=GMT%2B8&useSSL=true&useUnicode=true&characterEncoding=utf8
-
測試
@SpringBootTest class Springboot02DbApplicationTests { @Autowired DataSource dataSource; @Test void contextLoads() { System.out.println(dataSource.getClass()); } }
CRUD
-
Spring對原生的JDBC進行輕量級封裝,大大簡化了JDBC的操作。即使在沒有第三方ORM框架的情況下,也能完成一些簡單的CRUD操作
-
Spring將原生的JDBC封裝成了
JDBCTemplate
並完成了自動配置,我們直接拿來用就好了 -
Controller
@RestController public class JDBCController { @Autowired private JdbcTemplate template; @RequestMapping("/list") public List<Map<String, Object>> getAllDepartment() { String sql = "select * from springboot.department"; return template.queryForList(sql); } }
- 這邊是一個小技巧,在沒有實體類的情況下,可以使用map來裝載查詢出來的資料
4.3 整合Druid
-
Drudi號稱是Java中最好的資料庫連線池,他繼承了C3P0、DBCP 等 DB 池的優點,同時具有強大的日誌監控功能
-
這裡主要介紹的是它的監控功能
-
配置SpringBoot
- 要想使得SpringBoot切換連線池,我們可以通過
spring.datasource.type
屬性進行手動切換。
# 配置基本的資料庫連線資訊 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 url: jdbc:mysql://localhost:3306/springboot?serverTimezone=GMT%2B8&useSSL=true&useUnicode=true&characterEncoding=utf8 type: com.alibaba.druid.pool.DruidDataSource
- 要想使得SpringBoot切換連線池,我們可以通過
-
Druid
配置類,這裡順便複習一下Java配置類package com.pbx.config; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.Servlet; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; /** * @author BruceXu * @date 2020/12/17 */ @Configuration public class DruidConfig { @Bean @ConfigurationProperties("druid") public DataSource druidDataSource() { return new DruidDataSource(); } @Bean public ServletRegistrationBean<Servlet> druidServlet() { // 配置監控 ServletRegistrationBean<Servlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); Map<String, String> map = new HashMap<>(); //後臺管理介面的登入賬號密碼 map.put("loginUsername", "admin"); map.put("loginPassword", "123456"); // 訪問白名單 map.put("allow", ""); // 黑名單 map.put("deny", "192.168.1.1"); bean.setInitParameters(map); return bean; } }
-
這裡給出Druid可供配置的所有後臺引數
-
-
測試
-
排坑
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
-
使用JDBC時,使用第二個依賴,不要用第一個,不然會引起異常,排查時具體表現為 jdbc的url not set
-
4.4 整合MyBatis
匯入依賴
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
實體類
@Repository
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private int id;
private String name;
}
mapper介面
@Mapper
@Repository
public interface DepartmentMapper {
List<Department> getAllDepartment();
Department getDepartmentById(@Param("id") int id);
}
mapper.xml
- 記得在SpringBoot中配置這些配置檔案的位置,要不就啟用全域性的mybatis-config檔案進行配置,不然就會註冊不到mapper
<mapper namespace="com.pbx.mapper.DepartmentMapper">
<select id="getDepartmentList" resultType="com.pbx.pojo.Department">
select * from springboot.department
</select>
<select id="getDepartmentById" resultType="com.pbx.pojo.Department">
select * from springboot.department where id = #{id}
</select>
</mapper>
application.yaml
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
測試
@SpringBootTest
class Springboot03ApplicationTests {
@Autowired
private DataSource dataSource;
@Autowired
private DepartmentMapper mapper;
@Test
void contextLoads() {
System.out.println(dataSource.getClass());
List<Department> list = mapper.getDepartmentList();
System.out.println(list);
}
}