赞
踩
目录
3.1、第三方的依赖: *-spring-boot-starter
正常数据访问按照
第一步:导入数据库相关场景
第二步:配置数据库连接信息的配置项
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jdbc</artifactId>
- </dependency>
- <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>
- <version>2.3.2.RELEASE</version>
- <scope>compile</scope>
- </dependency>
- 内
- 数据库连接池
- <dependency>
- <groupId>com.zaxxer</groupId>
- <artifactId>HikariCP</artifactId>
- <version>3.4.5</version>
- <scope>compile</scope>
- </dependency>
数据库驱动?
为什么导入JDBC场景,官方不导入驱动?mysql-connector-java
因为官方不知道我们接下要操作什么数据库,不同的数据库对应的数据库驱动不同。
数据库版本和驱动版本对应
我的数据库版本:5.7.20
版本仲裁:mysql官方做了版本仲裁,驱动默认版本8.0.21
故需要将数据库版本5.7.20和驱动版本5.1.49 对应:
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.49</version>
- </dependency>
修改mysql驱动版本方法:
- 1、直接依赖引入具体版本(maven的就近依赖原则)
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.49</version>
- </dependency>
- 2、重新声明版本(maven的属性的就近优先原则)
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
-
- <properties>
- <java.version>1.8</java.version>
- <mysql.version>5.1.49</mysql.version>
- </properties>
自动配置的类
- @Configuration(proxyBeanMethods = false)
- @ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })
- @ConditionalOnMissingBean(type = "io.r2dbc.spi.ConnectionFactory")
- @EnableConfigurationProperties(DataSourceProperties.class)
- @Import({ DataSourcePoolMetadataProvidersConfiguration.class, DataSourceInitializationConfiguration.class })
- public class DataSourceAutoConfiguration {
-
-
- @Configuration(proxyBeanMethods = false)
- @Conditional(PooledDataSourceCondition.class)
- @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
- @Import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,
- DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.Generic.class,
- DataSourceJmxConfiguration.class })
- protected static class PooledDataSourceConfiguration {
-
- }
分析:
DataSourceProperties:spring.datasource 表示修改数据源的话,只需要在这里修改即可
- 源码:
- @ConfigurationProperties(prefix = "spring.datasource")
- public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
-
- private String driverClassName;
-
- private String url;
-
- private String username;
-
- private String password;
-
- private String jndiName;
- }
默认是Hikari数据源:
也可以通过spring.datasource.type = com.zaxxer.hikari.HikariDataSource来手动开启数据源为Hikari
- @Configuration(proxyBeanMethods = false)
- @ConditionalOnClass(HikariDataSource.class)
- @ConditionalOnMissingBean(DataSource.class)
- @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "com.zaxxer.hikari.HikariDataSource",
- matchIfMissing = true)
- static class Hikari {
-
- @Bean
- @ConfigurationProperties(prefix = "spring.datasource.hikari")
- HikariDataSource dataSource(DataSourceProperties properties) {
- HikariDataSource dataSource = createDataSource(properties, HikariDataSource.class);
- if (StringUtils.hasText(properties.getName())) {
- dataSource.setPoolName(properties.getName());
- }
- return dataSource;
- }
-
- }
- spring:
- datasource:
- url: jdbc:mysql://localhost:3306/db_account
- username: root
- password: 123456
- driver-class-name: com.mysql.jdbc.Driver
- jdbc:
- template:
- query-timeout: 3 #3s超时
- # main:
- # allow-bean-definition-overriding: true
- # type: com.zaxxer.hikari.HikariDataSource
- @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);
- }
-
- }
连接数据库时只需要在pom添加场景(默认添加了Hikari数据源),然后在配置文件些连接信息即可。当然也可以添加其他数据源。
https://github.com/alibaba/druid
整合第三方技术的两种方式
1、创建数据源(加依赖+加配置bean)
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.1.17</version>
- </dependency>
-
- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
- destroy-method="close">
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- <property name="maxActive" value="20" />
- <property name="initialSize" value="1" />
- <property name="maxWait" value="60000" />
- <property name="minIdle" value="1" />
- <property name="timeBetweenEvictionRunsMillis" value="60000" />
- <property name="minEvictableIdleTimeMillis" value="300000" />
- <property name="testWhileIdle" value="true" />
- <property name="testOnBorrow" value="false" />
- <property name="testOnReturn" value="false" />
- <property name="poolPreparedStatements" value="true" />
- <property name="maxOpenPreparedStatements" value="20" />
- </bean>
2、使用配置类代替配置bean
@ConfigurationProperties("spring.datasource"):将配置文件中的属性绑定到对象中
- @Configuration
- public class MyDataSourceConfig {
-
- //默认的自动配置是判断容器中没有才会配
- //@ConditionOnMissingBean(DataSource.class)
- @Bean
- @ConfigurationProperties("spring.datasource")//读取application.yml中的内容
- public DataSource dataSource(){
- DruidDataSource druidDataSource = new DruidDataSource();
-
- return druidDataSource;
- }
-
- }
- spring:
- datasource:
- url: jdbc:mysql://localhost:3306/mybatis
- username: root
- password: 123456
- driver-class-name: com.mysql.jdbc.Driver
- jdbc:
- template:
- query-timeout: 3
3、测试
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class SpringBootLoggingApplicationTests {
-
- @Autowired
- DataSource dataSource;
-
- @Autowired
- JdbcTemplate jdbcTemplate;
-
- @Test
- public void context(){
- Long aLong = jdbcTemplate.queryForObject("select count(*) from user", Long.class);
- LOGGER.info("记录总数:{}",aLong);
- //2021-12-08 00:09:11.984 INFO 30552 --- [ main] c.c.s.SpringBootLoggingApplicationTests : 记录总数:8
- LOGGER.info("数据源类型:{}",dataSource.getClass());
- //2021-12-08 00:20:13.188 INFO 31026 --- [ main] c.c.s.SpringBootLoggingApplicationTests : 数据源类型:class com.zaxxer.hikari.HikariDataSource$$EnhancerBySpringCGLIB$$ef95382c
- //2021-12-08 00:32:50.702 INFO 31548 --- [ main] c.c.s.SpringBootLoggingApplicationTests : 数据源类型:class com.alibaba.druid.pool.DruidDataSource
- }
- }
1、引入druid-starter
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid-spring-boot-starter</artifactId>
- <version>1.1.17</version>
- </dependency>
2、分析自动配置
- private static final String FILTER_STAT_PREFIX = "spring.datasource.druid.filter.stat";
- private static final String FILTER_CONFIG_PREFIX = "spring.datasource.druid.filter.config";
- private static final String FILTER_ENCODING_PREFIX = "spring.datasource.druid.filter.encoding";
- private static final String FILTER_SLF4J_PREFIX = "spring.datasource.druid.filter.slf4j";
- private static final String FILTER_LOG4J_PREFIX = "spring.datasource.druid.filter.log4j";
- private static final String FILTER_LOG4J2_PREFIX = "spring.datasource.druid.filter.log4j2";
- private static final String FILTER_COMMONS_LOG_PREFIX = "spring.datasource.druid.filter.commons-log";
- private static final String FILTER_WALL_PREFIX = "spring.datasource.druid.filter.wall";
3、配置示例
- spring:
- datasource:
- url: jdbc:mysql://localhost:3306/db_account
- username: root
- password: 123456
- driver-class-name: com.mysql.jdbc.Driver
-
- druid:
- aop-patterns: com.atguigu.admin.* #监控SpringBean
- filters: stat,wall # 底层开启功能,stat(sql监控),wall(防火墙)
-
- stat-view-servlet: # 配置监控页功能
- enabled: true
- login-username: admin
- login-password: admin
- resetEnable: false
-
- web-stat-filter: # 监控web
- enabled: true
- urlPattern: /*
- exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
-
-
- filter:
- stat: # 对上面filters里面的stat的详细配置
- slow-sql-millis: 1000
- logSlowSql: true
- enabled: true
- wall:
- enabled: true
- config:
- drop-table-allow: false
SpringBoot官方的Starter:spring-boot-starter-*
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>2.1.4</version>
- </dependency>
- public interface SqlSessionFactory {
- SqlSession openSession();
-
- }
- public class SqlSessionTemplate implements SqlSession, DisposableBean {
- private final SqlSessionFactory sqlSessionFactory;
- private final SqlSession sqlSessionProxy;
-
- }
-
- public interface SqlSession extends Closeable {
- <T> T selectOne(String var1);
-
- }
- @Configuration
- @ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
- @ConditionalOnSingleCandidate(DataSource.class)
- @EnableConfigurationProperties({MybatisProperties.class}): MyBatis配置项绑定类
- @AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class})
- public class MybatisAutoConfiguration implements InitializingBean {
-
- @Bean
- @ConditionalOnMissingBean
- public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
- }
-
- public static class AutoConfiguredMapperScannerRegistrar implements BeanFactoryAware, ImportBeanDefinitionRegistrar {
-
- }
-
- }
-
-
- @ConfigurationProperties(prefix = "mybatis"):配置文件以mybatis开头
- public class MybatisProperties{
-
- }
mybatis的全局配置文件
SQL映射文件
插件:mybatisX能够直接指向sql映射文件
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>2.1.4</version>
- </dependency>
- @Mapper
- public interface UserMapper {
-
- public User getUser(Long id);
- }
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <!--mapper为根元素,namespace指定了命名空间-->
- <mapper namespace="com.crane.springboot.mapper.UserMapper">
- <!--验证用户登录-->
- <select id="getUser" resultType="com.crane.springboot.domain.User">
- SELECT * FROM user WHERE id=#{id}
- </select>
- </mapper>
- <?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>
-
- <!-- 开启驼峰命名 :数据库字段名user_id 和对象属性对象 userId-->
- <settings>
- <setting name="mapUnderscoreToCamelCase" value="true"/>
- </settings>
-
- </configuration>
application.yml
- spring:
- datasource:
- url: jdbc:mysql://localhost:3306/mybatis
- username: root
- password: 123456
- driver-class-name: com.mysql.jdbc.Driver
- jdbc:
- template:
- query-timeout: 3
- # main:
- # allow-bean-definition-overriding: true
- # type: com.zaxxer.hikari.HikariDataSource
-
- # 配置mybatis规则
- mybatis:
- # config-location: classpath:mybatis/mybatis-config.xml
- mapper-locations: classpath:mybatis/mapper/*.xml
- configuration:
- map-underscore-to-camel-case: true
- @Controller
- @Slf4j
- public class UserController {
-
- @Autowired
- private UserService userService;
-
- //http://localhost:8080/user?id=1
- //{"id":1,"name":"xiao","pwd":123}
- @ResponseBody
- @GetMapping("/user")
- public User getUserById(@RequestParam("id") Long id){
- return userService.gerUserById(id);
- }
- }
-
- @Service
- public class UserService {
-
- @Autowired
- UserMapper userMapper;
-
- public User gerUserById(Long id){
- return userMapper.getUser(id);
- }
- }
-
- @Data
- public class User {
-
- private Long id;
- private String name;
- private Integer pwd;
- }
注意:
可以删除全局配置文件mybatis-config.xml。将全局配置文件中的内容放到 application.yml中配置即可:配置 private Configuration configuration;
mybatis.configuration下面的所有,就是相当于改mybatis全局配置文件中的值:
- # 配置mybatis规则
- mybatis:
- mapper-locations: classpath:mybatis/mapper/*.xml
- configuration:
- map-underscore-to-camel-case: true
-
- 可以不写全局;配置文件,所有全局配置文件的配置都放在configuration配置项中即可
- @Mapper
- public interface UserMapper {
-
- @Select("select * from city where id=#{id}")
- public User getById(Long id);
-
- public void insert(User user);
-
- }
- @Mapper
- public interface UserMapper {
-
- @Select("SELECT * FROM user WHERE id=#{id}")
- public User getUser(Long id);
-
- public void insert(User user);
- }
-
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <!--mapper为根元素,namespace指定了命名空间-->
- <mapper namespace="com.crane.springboot.mapper.UserMapper">
- <insert id="insert">
- insert into user(`name`,`pwd`) values (#{name},#{pwd})
- </insert>
- </mapper>
-
controller
- @Controller
- @Slf4j
- public class UserController {
-
- @Autowired
- private UserService userService;
-
-
- @ResponseBody
- @PostMapping("/save/user")
- public User saveUser(User user){
- userService.saveUser(user);
- return user;
- }
- }
postman模拟表单提交post
返回自增的id值
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-
- <mapper namespace="com.crane.springboot.mapper.UserMapper">
- <insert id="insert" useGeneratedKeys="true" keyProperty="id">
- insert into user(`name`,`pwd`) values (#{name},#{pwd})
- </insert>
-
- </mapper>
insert可以改成注解形式
- @Mapper
- public interface UserMapper {
-
- @Select("SELECT * FROM user WHERE id=#{id}")
- public User getUser(Long id);
-
- @Insert("insert into user(`name`,`pwd`) values (#{name},#{pwd})")
- @Options(useGeneratedKeys = true, keyProperty = "id")
- public void insert(User user);
- }
@MapperScan("com.admin.mapper") 简化:
可以在启动类上添加@MapperScan(“...”), 其他的接口就可以不用标注@Mapper注解
- @SpringBootApplication
- @MapperScan("com.crane.springboot")
- @Slf4j
- public class HelloWorldMainApplication {
- public static void main(String[] args) {
- //该类必须是@SpringBootApplication标注的类
- ConfigurableApplicationContext applicationContext = SpringApplication.run(HelloWorldMainApplication.class);
- System.out.println("正常启动");
- log.info("系统正常启动");
- }
- }
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
建议安装 MybatisX 插件
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>3.4.1</version>
- </dependency>
自动配置
优点:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。