1、导入JDBC 模板对应jar包
<!--jdbcTemplate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2、配置数据库链接信息(yml或者properties内编写)
3、编写配置类,并注入Bean,默认数据源为:Hikari
package com.ZQQQ.config;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**druid 配置
* JDBCTemplteConfig 配置
*/
@SpringBootTest
public class JDBCTemplteConfig {
@Autowired
DataSource dataSource;
@Test
void contextLoads(){
System.out.println(dataSource.getClass());
try {
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
4、编写测试用例
package com.ZQQQ.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* JDBCTemplte模板
*/
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
/**
* 查询user 表的全部信息
*
* List集合中的对象是一个Map对象,而这个Map对象的键是String类型,值是Object类型
*/
@GetMapping("/UserList")
public List<Map<String,Object>> UserList(){
String sql="select * from user";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
//自动提交事务
@RequestMapping("/inserUser")
public String insertUser(){
String sql ="insert into user(name,age,email,create_time,modife_time,version)VALUES('五花肉',18,'78956670@qq.com','2021-08-12','2021-08-12',1)";
jdbcTemplate.update(sql);
return "successful";
}
@GetMapping("/updateUser")
public String updateUser(){
String sql ="update user set create_time='2021-08-01',modife_time ='2021-08-01' where id=9";
jdbcTemplate.update(sql);
return "successful";
}
@GetMapping("/deleteUesr")
public String deleteUesr(){
String sql ="delete from user where id =14";
jdbcTemplate.update(sql);
return "successful";
}
}
总结:
如上省略了Mybatis 层,直接去操作数据库的,这样的方式不常用。