一、JDBC
1、pom文件
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- SpringBoot集成的JDBC以及数据库连接包 -->
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2、配置文件application.yml
spring:
datasource:
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC
3、测试代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJdbcApplicationTests {
@Autowired
private DataSource dataSource;
@Test
public void test() throws SQLException {
Connection data = dataSource.getConnection();
System.out.println("------" + data.getClass());
System.out.println("------" + dataSource.getClass());
data.close();
}
}
4、查询数据库
@Controller
public class HelloController {
@Autowired
JdbcTemplate jdbcTemplate;
@GetMapping("/query")
@ResponseBody
public Map<String,Object> query(){
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from department");
return list.get(0);
}
}
二、整合Druid数据源
1、pom文件中添加数据源好日志文件
<!--引入druid数据源-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、配置数据源
spring:
datasource:
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
还是运行上述测试代码:
3、 使配置生效
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
4、访问:http://localhost:8080/druid/login.html
账号:admin,密码:123456
eg:当发送http://localhost:8080/query请求时,会在sql监控中看到监控结果,web应用中也可看到相关执行情况
三、整合mybatis
1、引入mybatis依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
2、注解版
(1)mapper文件:
@Mapper
public interface DepartmentMapper {
@Select("select * from department where id = #{id}")
public Department getDeptById(Integer id);
@Delete("delete from department where id = #{id}")
public int deleteDeptById(Integer id);
@Insert("insert into department(departmentName) values(#{departmentName})")
public int insertDept(Department department);
@Update("update department set departmentName = #{departmentName} where id = #{id}")
public int updateDept(Department department);
}
(2)Controller
@RestController
public class DepartmentController {
@Autowired
private DepartmentMapper departmentMapper;
@GetMapping("/dept/{id}")
public Department getDeptById(@PathVariable("id") Integer id){
return departmentMapper.getDeptById(id);
}
@Options(useGeneratedKeys = true,keyProperty = "id")
@GetMapping("/delDept/{id}")
public int deleteDeptById(@PathVariable("id") Integer id){
return departmentMapper.deleteDeptById(id);
}
@GetMapping("/dept")
public Department insertDept(Department department){
departmentMapper.insertDept(department);
return department;
}
}
访问:http://localhost:8080/dept/2
访问:http://localhost:8080/dept?departmentName=3as
(3)问题:如果数据库中的字段是department_name,如何开启驼峰命名的方式呢
数据库字段名如下:
Mapper代码修改为如下;Controller层代码不变;访问方式不变
(4)改进:如果mapper文件很多,那么需要给每一个mapper文件都加上@Mapper注解,可以使用如下方式替代
使用@Mapper或者@MapperScan将接口扫描装配到容器中
3、配置文件版
(1)mapper文件
//使用@Mapper或者@MapperScan将接口扫描装配到容器中
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
public void insertEmp(Employee employee);
}
(2)mapper.xml文件
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.springboot.mapper.EmployeeMapper">
<!-- public Employee getEmpById(Integer id);
public void insertEmp(Employee employee);-->
<select id="getEmpById" resultType="com.atguigu.springboot.bean.Employee">
SELECT * FROM employee WHERE id=#{id}
</select>
<insert id="insertEmp" useGeneratedKeys="true" keyProperty="id">
INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
</insert>
</mapper>
(3)mybatis配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
(4)全局配置文件
mybatis:
# 指定全局配置文件位置
config-location: classpath:mybatis/mybatis-config.xml
# 指定sql映射文件位置
mapper-locations: classpath:mybatis/mapper/*.xml
(5)Controller文件
@RestController
public class EmployeeController {
@Autowired
private EmployeeMapper employeeMapper;
@GetMapping("/emp/{id}")
public Employee getEmpById(@PathVariable("id") Integer id){
return employeeMapper.getEmpById(id);
}
@GetMapping("/emp")
public Employee insertEmp(Employee employee){
employeeMapper.insertEmp(employee);
return employee;
}
}
(6)项目结构
(7)测试
访问:http://localhost:8080/emp/1
访问:http://localhost:8080/emp?lastName=zhang&email=111213@qq.com&gender=1&dId=2