06、数据访问
1、SQL 1、数据源的自动配置-HikariDataSource 1、导入JDBC场景org.springframework.boot spring-boot-starter-data-jdbc
导入JDBC场景的动器会帮我们导入了这些组件,比如 数据源HikariDataSource,我们就可以在数据源里获取数据库连接做增删改查的操作。
数据库驱动为什么没有导入?
为什么导入JDBC场景,官方不导入驱动?官方不知道我们接下要操作什么数据库Oracle、Myql。
数据库版本和驱动版本对应
spingboot,Mysql驱动默认版本:2、分析自动配置 1、自动配置的类8.0.22 如果Mysql使用的5版本,想要修改版本:两种方式 1、直接依赖引入具体版本(原理:maven的就近依赖原则) 2、重新声明版本(maven的属性的就近优先原则) mysql mysql-connector-java 1.8 5.1.49
帮我们配置底层的数据库连接池,及其他组件
DataSourceAutoConfiguration : 数据源的自动配置 修改数据源相关的配置:spring.datasource 数据库连接池的配置,是自己容器中没有DataSource才自动配置的,利用的@ConditionalOnMissBean注解 数据源:底层配置好的连接池是:HikariDataSource
@Configuration(proxyBeanMethods = false)
@Conditional(PooledDataSourceCondition.class)
@ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
@import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,
DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.OracleUcp.class,
DataSourceConfiguration.Generic.class, DataSourceJmxConfiguration.class })
protected static class PooledDataSourceConfiguration
也帮我们配置了事务的,JdbcTemplate
● DataSourceTransactionManagerAutoConfiguration: 事务管理器的自动配置 ● JdbcTemplateAutoConfiguration: JdbcTemplate的自动配置,可以来对数据库进行crud(了解) ○ 可以修改这个配置项@ConfigurationProperties(prefix = "spring.jdbc") 来修改JdbcTemplate ○ 程序启动 会通过@Bean@Primary *自动将JdbcTemplate对象放入容器*;容器中有这个组件 ● JndiDataSourceAutoConfiguration: jndi的自动配置 ● XADataSourceAutoConfiguration: 分布式事务相关的(了解)3、修改配置项
数据库连接地址
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_account
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
4、测试
@Slf4j
@SpringBootTest
class Boot05WebAdminApplicationTests {
@Autowired
JdbcTemplate jdbcTemplate;
@Test
void contextLoads() {
// jdbcTemplate.queryForObject("select * from account_tbl")
// jdbcTemplate.queryForList("select * from account_tbl",)
Long aLong = jdbcTemplate.queryForObject("select count(*) from account_tbl", Long.class);
log.info("记录总数:{}",aLong);
}
}
2、使用Druid数据源(阿里,第三方)
1、druid官方github地址
https://github.com/alibaba/druid
整合第三方技术的两种方式
自定义
找starter
2、自定义方式
1、创建数据源
引入数据源
com.alibaba druid 1.1.17
自定义数据源,新建配置类+yaml
@ConfigurationProperties("spring.datasource")
@Bean
public DataSource dataSource(){
DruidDataSource druidDS = new DruidDataSource();
//druidDS.setUrl(); 我们自定义配置数据源,那么还需要配置数据库连接地址,
//druidDS.setUsername();这样set很麻烦,所以就可以加通过@ConfigurationProperties("spring.datasource")进行配置绑定
return druidDS;
} }
spring:
datasource:
url: jdbc:mysql://localhost:3306/his
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
测试
有以下功能:
StatViewServlet的用途包括:
提供监控信息展示的html页面,之前是通过配置StatViewServlet放入容器总 如下xml配置
提供监控信息的JSON API
DruidStatView com.alibaba.druid.support.http.StatViewServlet DruidStatView /druid @ResponseBody @GetMapping({"/","/login"}) public UserInfo loginIndex(@RequestParam("id") Long id){ return indexService.getUserInfo(id); } }
@Service
public class IndexService {
@Autowired
private UserInfoMapper userInfoMapper;
public UserInfo getUserInfo(Long id){
UserInfo userInfo = userInfoMapper.getUserInfo(id);
return userInfo;
}
}
浏览器返回结果:
注意:数据的字段如果是user_id 在映射到实体类字段userId会映射不上,因为Mybatis的驼峰命名法默认为false,
这样配置
配置 private Configuration configuration; mybatis.configuration下面的所有,就是相当于改mybatis全局配置文件中的值,所以这种方式也是可以的
@Mapper
public interface CityMapper {
@Select("select * from city where id=#{id}")
public City getById(Long id);
public void insert(City city);
}
3、混合模式@Mapper
public interface CityMapper {
@Select("select * from city where id=#{id}")
public City getById(Long id);
public void insert(City city);
}
最佳实战:
引入mybatis-starter
配置application.yaml中,指定mapper-location位置即可
编写Mapper接口并标注@Mapper注解
简单方法直接注解方式
复杂方法编写mapper.xml进行绑定映射
@MapperScan("com.atguigu.admin.mapper") 简化,其他的接口就可以不用标注@Mapper注解
4、整合 MyBatis-Plus 完成CRUD
1、什么是MyBatis-Plus
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
mybatis plus 官网
建议安装 MybatisX 插件
com.baomidou mybatis-plus-boot-starter 3.4.1
自动配置
MybatisPlusAutoConfiguration 配置类,MybatisPlusProperties 配置项绑定。mybatis-plus:xxx 就是对mybatis-plus的定制
SqlSessionFactory 自动配置好。底层是容器中默认的数据源
mapperLocations 自动配置好的。有默认值。classpath*:/mapper*.xml;任意包的类路径下的所有mapper文件夹下任意路径下的所有xml都是sql映射文件。 建议以后sql映射文件,放在 mapper下
容器中也自动配置好了 SqlSessionTemplate
@Mapper 标注的接口也会被自动扫描;建议直接 @MapperScan("com.atguigu.admin.mapper") 批量扫描就行
优点:
只需要我们的Mapper继承 baseMapper 就可以拥有crud能力3、CRUD功能
@GetMapping("/user/delete/{id}")
public String deleteUser(@PathVariable("id") Long id,
@RequestParam(value = "pn",defaultValue = "1")Integer pn,
RedirectAttributes ra){
userService.removeById(id);
ra.addAttribute("pn",pn);
return "redirect:/dynamic_table";
}
@GetMapping("/dynamic_table")
public String dynamic_table(@RequestParam(value="pn",defaultValue = "1") Integer pn,Model model){
//表格内容的遍历
// response.sendError
// List users = Arrays.asList(new User("zhangsan", "123456"),
// new User("lisi", "123444"),
// new User("haha", "aaaaa"),
// new User("hehe ", "aaddd"));
// model.addAttribute("users",users);
//
// if(users.size()>3){
// throw new UserTooManyException();
// }
//从数据库中查出user表中的用户进行展示
//构造分页参数
Page page = new Page<>(pn, 2);
//调用page进行分页
Page userPage = userService.page(page, null);
// userPage.getRecords()
// userPage.getCurrent()
// userPage.getPages()
model.addAttribute("users",userPage);
return "table/dynamic_table";
}
@Service public class UserServiceImpl extends ServiceImplimplements UserService { } public interface UserService extends IService { }



