-
Spring Data简介:
-
对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系型数据库),Spring Boot 底层都是采用 Spring Data 的方式进行统一处理。
-
Spring Boot 底层都是采用 Spring Data 的方式进行统一处理各种数据库,Spring Data 也是 Spring 中与 Spring Boot、Spring Cloud 等齐名的知名项目。
-
Sping Data 官网:https://spring.io/projects/spring-data
-
-
整合过程:
2.1 导入依赖:Web、Jdbc API、Mysql Driver
成功后在pom.xml会有:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.2 yaml配置文件连接数据库
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
------
driver-class-name: com.mysql.cj.jdbc.Driver
------
2.3 测试是非连接成功:
@SpringBootTest
class SpringbootDataJdbcApplicationTests {
//DI注入数据源
@Autowired
DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
//看一下默认数据源
System.out.println(dataSource.getClass());
//获得连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
//关闭连接
connection.close();
}
}
- 测试类:
@RestController
public class JDBCtemplate {
@Autowired
JdbcTemplate jdbcTemplate;
@GetMapping("/hello")
public List<Map<String,Object>> getEmp(){
String sql = "select * from tbl_dept";
List<Map<String,Object>> list_map = jdbcTemplate.queryForList(sql);
return list_map;
}
@RequestMapping("/addEmp")
public String addDept(){
String sql = "insert into tbl_dept(id,dept_name) values (3,'财务部')";
jdbcTemplate.update(sql);
return "---------------Success---------------";
}
@RequestMapping("/deleteEmp/{id}")
public String deleteEmpById(@PathVariable("id") int id){
String sql = "delete from tbl_dept where id=?";
jdbcTemplate.update(sql,id);
return "---------------Success2---------------";
}
@RequestMapping("/updateEmp/{id}")
public String updateEmp(@PathVariable("id") int id){
String sql = "update tbl_dept set dept_name=? where id="+id;
Object ob = "天安部";
jdbcTemplate.update(sql,ob);
return "delete->success";
}
}
转载至:添加链接描述