1、整合基本JDBC与数据源 1.1 Spring官网 查看各种场景JDBC有关的场景启动器。
1 2 3 4 5 6 7 8 9 <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 >
配置文件:
1 2 3 4 5 6 spring: datasource: username: root password: 123456 url: jdbc:mysql://192.168.15.22:3306/jdbc driver-class-name: com.mysql.jdbc.Driver
效果:
默认是用org.apache.tomcat.jdbc.pool.DataSource作为数据源
数据源的相关配置都在DataSourceProperties里面
1.2 自动配置原理 org.springframework.boot.autoconfigure.jdbc
参考DataSourceConfiguration,根据配置创建数据源,默认使用Tomcat连接池;可以使用spring.datasource.type指定自定义的数据源类型;
SpringBoot默认可以支持以下数据源:
1 2 3 org.apache.tomcat.jdbc.pool.DataSource HikariDataSource BasicDataSource
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @ConditionalOnMissingBean ({DataSource.class }) @ConditionalOnProperty ( name = {"spring.datasource.type" }) static class Generic { Generic() { } @Bean public DataSource dataSource (DataSourceProperties properties) { return properties.initializeDataSourceBuilder().build(); } }
2、整合Druid数据源 在Maven公共库 中搜索Druid,找到其Maven依赖:
1 2 3 4 5 6 <dependency > <groupId > com.alibaba</groupId > <artifactId > druid</artifactId > <version > 1.1.23</version > </dependency >
在配置文件中加入配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 spring: datasource: username: root password: 123456 url: jdbc:mysql://192.168.8.156:3306/jdbc driver-class-name: com.mysql.jdbc.Driver 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: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
想要配置生效,导入druid数据源
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 @Configuration public class DruidConfig { @ConfigurationProperties (prefix = "spring.datasource" ) @Bean public DataSource druid () { return new DruidDataSource(); } @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; } @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; } }
在之前写的SpringinitializrApplicationTests
类的testJDBC()
方法中
1 System.out.println(dataSource.getClass());
语句打上断点,debug测试方法,查看控制台:
3、整合MyBatis 同样在Maven公共库 中搜索MyBatis Spring Boot Starter,找到其Maven依赖
1 2 3 4 5 6 <dependency > <groupId > org.mybatis.spring.boot</groupId > <artifactId > mybatis-spring-boot-starter</artifactId > <version > 1.3.5</version > </dependency >
3.1 MyBatis-Spring-Boot-Starter 简介 MyBatis-Spring-Boot-Starter类似一个中间件,链接Spring Boot和MyBatis,构建基于Spring Boot的MyBatis应用程序。
MyBatis-Spring-Boot-Starter 当前版本是 2.1.3,发布于2020年6月
MyBatis-Spring-Boot-Starter是个集成包,因此对MyBatis、MyBatis-Spring和SpringBoot的jar包都存在依赖,如下所示:
MyBatis-Spring-Boot-Starter
MyBatis-Spring
Spring Boot
Java
2.1
2.0 (need 2.0.2+ for enable all features)
2.1 or higher
8 or higher
1.3
1.3
1.5
6 or higher
3.2 分析依赖
依赖会引入spring-boot-starter-jdbc
,mybatis
的jar包,mybatis-spring
中间整合包以及mybatis-spring-boot-autoconfigure
自动配置包。
3.3 使用步骤
配置数据源相关属性
给数据库建表
创建JavaBean
注解版
3.4 注解版 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 @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) ; @Options (useGeneratedKeys = true , keyProperty = "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) ; }
访问方式:
问题:自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 @org .springframework.context.annotation.Configurationpublic class MyBatisConfig { @Bean public ConfigurationCustomizer configurationCustomizer () { return new ConfigurationCustomizer(){ @Override public void customize (Configuration configuration) { configuration.setMapUnderscoreToCamelCase(true ); } }; } }
还有,当我们实体类增多,每个映射文件都需要@Mapper
注解?可以在启动类中 使用MapperScan
批量扫描所有的Mapper接口;
点击MapperScan
查看源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 @Retention (RetentionPolicy.RUNTIME)@Target ({ElementType.TYPE})@Documented @Import ({MapperScannerRegistrar.class }) public @interface MapperScan { String[] value() default {}; String[] basePackages() default {}; Class<?>[] basePackageClasses() default {}; Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class ; Class<? extends Annotation> annotationClass() default Annotation.class ; Class<?> markerInterface() default Class.class ; String sqlSessionTemplateRef () default "" ; String sqlSessionFactoryRef () default "" ; Class<? extends MapperFactoryBean> factoryBean() default MapperFactoryBean.class ; }
里面可以配置basePackages()
参数:
1 2 3 4 5 6 7 8 9 10 11 @MapperScan ("com.initializr.mapper" )@SpringBootApplication public class SpringinitializrApplication { public static void main (String[] args) { System.out.println("Start..." ); SpringApplication.run(SpringinitializrApplication.class , args ) ; System.out.println("Success..." ); } ... }
3.5 配置文件版 MyBatis代码都托管到了GitHub,去GitHub 查看配置文件写法,官方文档
1 2 3 4 5 6 7 8 9 10 <?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 >
使配置文件生效:
1 2 3 4 5 6 mybatis: config-location: classpath:mybatis/mybatis-config.xml mapper-locations: classpath:mybatis/mapper/*.xml
更多使用参照官方文档
4、整合SpringData的JPA模块 4.1 SpringData简介 SpringData官方文档
Spring Data项目的目的是为了简化构建基于Spring框架应用的数据访问技术,包括非关系数据库、Map-Reduce框架、云数据服务等等;另外一位包含对关系数据库的访问支持。
应用面向Spring Data编程,使用其提供模板。
4.2 整合SpringData JPA 引入启动器:
1 2 3 4 5 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-data-jpa</artifactId > </dependency >
查看视图:
可以看出,其导入了很多Spring业务功能模块,比如AOP和事务(Spring-tx)等;
还可以看出其底层是用hibernate实现的,其中使用hibernate-entitymanager
管理hibernate-jpa-*-ap
,进行操作。
依然需要配置数据源,用JPA操作数据库。
JPA:ORM(Object Relational Mapping);
编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Entity @Table (name = "tbl_user" ) public class User { @Id @GeneratedValue (strategy = GenerationType.IDENTITY) private Integer id; @Column (name = "last_name" ,length = 50 ) private String lastName; @Column private String email; }
编写一个Dao接口来操作实体类对应的数据表(称为Repository)
1 2 3 public interface UserRepository extends JpaRepository <User ,Integer > {}
1 2 3 4 5 6 7 spring: jpa: hibernate: ddl-auto: update show-sql: true
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 @RestController public class UserController { @Autowired UserRepository userRepository; @GetMapping ("/user/{id}" ) public User getUser (@PathVariable("id" ) Integer id) { User user = userRepository.findOne(id); return user; } @GetMapping ("/user" ) public User insertUser (User user) { User save = userRepository.save(user); return save; } }
写了两个简单的方法用来做测验
测试成功啦!