Spring Data JPA 从入门到精通~默认数据源的讲解

默认数据源

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

但是在实际工作中不可能这么简单,因为会用其他数据源,而不是用的默认数据源。我们先来一步一步了解一下,一起来开启探索它默认的数据源之旅吧。

通过三种方法来查看默认的 DataSource 是什么

(1)日志法:在 application.properties 增加如下配置

logging.level.org.springframework=DEBUG

然后当我们启动成功之后,通过开发工具 Intellij IDEA 的 Debug 的 Console 控制台,搜索“DataSource”,找到了如下日志,发现它默认是 JDBC 的 Pool 的 DataSource。

spring.datasource.type=com.zaxxer.hikari.HikariDataSource,需要注意的是这是 Spring Boot 2.0 里面的新特性,代替了 1.5** 版本里面的 org.apache.tomcat.jdbc.pool.DataSource 的数据源,hikari 的口碑可以性能测试行业内的口碑逐渐代替了 Tomcat 的 datasource。

(2)Debug 方法:在 manager 里面的如下代码

在“userRepository.findByLastName(names);” 设置一个断点,然后请求一个 URL 让断点进来,然后通过开发工具 Intellij IDEA 的 Debug 的 Memory View 视图,里面搜索

也能发现 DataSource,然后双击就能看到我们想看的内容。

(3)最原理的方法、最常用的、原理分析方法

回到 QuickStartApplication,单击 @SpringBootApplication 查看其源码关键部分如下:

@SpringBootConfiguration@EnableAutoConfigurationpublic @interface SpringBootApplication {......}

打开 @EnableAutoConfiguration 所在 JAR 包,打开 spring-boot-autoconfigure-2.0.0.RELEASE.jar/META-INF/spring.factories 文件,发现如下内容:

//# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
......
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration打开 JpaRepositoriesAutoConfiguration 类,内容如下:
@Configuration
@ConditionalOnBean(DataSource.class)
@ConditionalOnClass(JpaRepository.class)
@ConditionalOnMissingBean({ JpaRepositoryFactoryBean.class,JpaRepositoryConfigExtension.class })
@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled", havingValue = "true", matchIfMissing = true)
@Import(JpaRepositoriesAutoConfigureRegistrar.class)
@AutoConfigureAfter(HibernateJpaAutoConfiguration.class)
public class JpaRepositoriesAutoConfiguration {
}

这时候可以发现,如果使用了 Spring Boot 的注解方式和传统的 XML 配置方式是有优先级的,如果配置了 XML 中的 JpaRepositoryFactoryBean,那么就会沿用 XML 配置的一整套,而通过 @ConditionalOnMissingBean 这个注解来判断,就不会加载 Spring Boot 的 JpaRepositoriesAutoConfiguration 此类的配置,还有就是前提条件 DataSource 和 JpaRepository 必须有相关的 Jar 存在。

打开 HibernateJpaAutoConfiguration 类:

@Configuration
@ConditionalOnClass({ LocalContainerEntityManagerFactoryBean.class, EntityManager.class })
@Conditional(HibernateEntityManagerCondition.class)
@AutoConfigureAfter({ DataSourceAutoConfiguration.class })
public class HibernateJpaAutoConfiguration extends JpaBaseConfiguration {......}

这个时候发现了 DataSourceAutoConfiguration 的配置类即 datasource 的配置内容有哪些?

打开 DataSourceAutoConfiguration,此时发现了我们最关键的类出现了。

@Configuration
@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })
@EnableConfigurationProperties(DataSourceProperties.class)
@Import({ DataSourcePoolMetadataProvidersConfiguration.class,DataSourceInitializationConfiguration.class })
public class DataSourceAutoConfiguration {......}

先看 DataSourcePoolMetadataProvidersConfiguration 类吧,内容如下:

@Configuration
public class DataSourcePoolMetadataProvidersConfiguration {//tomcat.jdbc.pool.DataSource前提条件需要引入tomcat-jdbc.jar@Configuration@ConditionalOnClass(org.apache.tomcat.jdbc.pool.DataSource.class)static class TomcatDataSourcePoolMetadataProviderConfiguration {@Beanpublic DataSourcePoolMetadataProvider tomcatPoolDataSourceMetadataProvider() {return (dataSource) -> {if (dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource) {return new TomcatDataSourcePoolMetadata((org.apache.tomcat.jdbc.pool.DataSource) dataSource);}return null;};}}//HikariDataSource.class前提需要引入HikariCP-2.7.8.jar@Configuration@ConditionalOnClass(HikariDataSource.class)static class HikariPoolDataSourceMetadataProviderConfiguration {@Beanpublic DataSourcePoolMetadataProvider hikariPoolDataSourceMetadataProvider() {return (dataSource) -> {if (dataSource instanceof HikariDataSource) {return new HikariDataSourcePoolMetadata((HikariDataSource) dataSource);}return null;};}}//CommonsDbcp 数据源,前提也是需要引入CommonsDbcp**.jar@Configuration@ConditionalOnClass(BasicDataSource.class)static class CommonsDbcp2PoolDataSourceMetadataProviderConfiguration {@Beanpublic DataSourcePoolMetadataProvider commonsDbcp2PoolDataSourceMetadataProvider() {return (dataSource) -> {if (dataSource instanceof BasicDataSource) {return new CommonsDbcp2DataSourcePoolMetadata((BasicDataSource) dataSource);}return null;};}}
}

通过查看它的代码可发现,Spring Boot 为我们的 DataSource 提供了最常见的三种默认配置:

  • HikariDataSource
  • Tomcat 的 JDBC
  • Apache 的 dbcp

而最终用哪个?就看你引用了哪个 datasoure 的 jar 包了。因为开篇的案例用的是 Spring Boot 2.0 的默认配置,而 2.0 放弃了默认引用的 Tomcat 的容器,而选用了 HikariDataSource 的配置,成为了 Java 语言里面公认的好的 data source,所以默认用的是 Hikari 的 DataSource 及其 HikariDataSourcePoolMetadata 连接池。当我们引用了 Jetty 或者 netty 等容器,连接池和 datasource 的实现方式也会跟着变的。

Datasource 和 JPA 都有哪些配置属性

我们接着上面的类 DataSourceAutoConfiguration,通过 @EnableConfigurationProperties(DataSourceProperties.class) 找到了 datasource 该如何配置,打开 DataSourceProperties 源码:

@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourcePropertiesimplements BeanClassLoaderAware, EnvironmentAware, InitializingBean {
/*** Name of the datasource.*/
private String name = "testdb";
/*** Generate a random datasource name.*/
private boolean generateUniqueName;
/*** Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.*/
private String driverClassName;
/*** JDBC url of the database.*/
private String url;
/*** Login user of the database.*/
private String username;
/*** Login password of the database.*/
private String password;
/*** JNDI location of the datasource. Class, url, username & password are ignored when* set.*/
private String jndiName;
......//如果还有一些特殊的配置直接看这个类的源码即可。
}

看到了配置数据的关键的几个属性的配置,及其一共有哪些属性值可以去配置。@ConfigurationProperties(prefix = "spring.datasource") 这个告诉我们 application.properties 里面的 datasource 相关的配置必须有 spring.datasource 开头,这样当启动的时候 DataSourceProperties 就会自动加载进来 datasource 的一切配置。正如我们前面配置的一样:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=jack
spring.datasource.password=jack123

......这里省略了一些其他datasource的key配置。

其实到这里如果自定义配置时也可以学习 Spring Data 的这种 properteis 的加载方式自定义**Properties.java,包括 DataSource 的配置方法,可以借鉴当时写的framework.jar。

JpaBaseConfiguration

我们回过头来再来看 HibernateJpaAutoConfiguration 的父类 JpaBaseConfiguration 打开关键内容如下:

@EnableConfigurationProperties(JpaProperties.class)
@Import(DataSourceInitializedPublisher.Registrar.class)
public abstract class JpaBaseConfiguration implements BeanFactoryAware {private final DataSource dataSource;private final JpaProperties properties;
......}

这个时候发现了 JpaProperties 类:

@ConfigurationProperties(prefix = "spring.jpa")
public class JpaProperties {//jpa原生的一些特殊属性private Map<String, String> properties = new HashMap<String, String>();//databasePlatform名字,默认和Database一样。private String databasePlatform;//数据库平台MYSQL、DB2、H2......private Database database;//是否根据实体创建Ddlprivate boolean generateDdl = false;//是否显示sql,默认不显示private boolean showSql = false;private Hibernate hibernate = new Hibernate();
......
}

此时再打开 Hibernate 类:

public static class Hibernate {
private String ddlAuto;
/*** Use Hibernate's newer IdentifierGenerator for AUTO, TABLE and SEQUENCE. This is* actually a shortcut for the "hibernate.id.new_generator_mappings" property.* When not specified will default to "false" with Hibernate 5 for back* compatibility.*/
private Boolean useNewIdGeneratorMappings;
@NestedConfigurationProperty
private final Naming naming = new Naming();
......//我们看到Hibernate类就这三个属性。
}

再打开 Naming 源码看一下命名规范:

public static class Naming {private static final String DEFAULT_HIBERNATE4_STRATEGY = "org.springframework.boot.orm.jpa.hibernate.SpringNamingStrategy";private static final String DEFAULT_PHYSICAL_STRATEGY = "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy";private static final String DEFAULT_IMPLICIT_STRATEGY = "org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy";/*** Hibernate 5 implicit naming strategy fully qualified name.*/private String implicitStrategy;/*** Hibernate 5 physical naming strategy fully qualified name.*/private String physicalStrategy;/*** Hibernate 4 naming strategy fully qualified name. Not supported with Hibernate* 5.*/private String strategy;
......}

看到这里面 Naming 命名策略,兼容了 Hibernate4 和 Hibernate5 并且给出了默认的策略,后面章节我们做详细解释。

所以配置文件中关于 JPA 的配置基本上就这些配置项。

spring.jpa.database-platform=mysql
spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.type=trace
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.jdbc.batch_size=50

Configuration 思路,实战学习方法

其实在实际工作中,若遇到问题,经常看到开发人员去百度进行狂搜,看看怎么配置的,然后试了了半天发现怎么配置都没效果。其实这里给大家提供了一个思路,我们在找配置项的时候,看看源码都支持哪些 key,而这些 key 分别代表什么意思然后再到百度搜索,这样我们能对症下药,正确完美的完成我们的配置文件的配置。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/496298.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

国内AI芯片百家争鸣,何以抗衡全球技术寡头

来源&#xff1a;中国科学院自动化研究所 作者&#xff1a;吴军宁如果说 2016 年 3 月份 AlphaGo 与李世石的那场人机大战只在科技界和围棋界产生较大影响的话&#xff0c;那么 2017 年 5 月其与排名第一的世界围棋冠军柯洁的对战则将人工智能技术推向了公众视野。阿尔法狗&am…

zabbix php 5.6 安装配置,CentOS 5.6下Zabbix 1.8.5 服务端安装部署

CentOS 5.6下Zabbix 1.8.5 服务端安装部署CentOS 5.6 x86_64 Zabbix 1.8.5IP:192.168.88.130一、安装LAMP环境依赖包&#xff1a;# yum install MySQL-server mysql-devel libcurl-devel net-snmp-devel php php-gd php-xml php-mysql php-mbstring php-bcmath httpd curl-dev…

Linux系统编程——I/O多路复用select、poll、epoll

参考&#xff1a;https://segmentfault.com/a/1190000003063859 Linux下的I/O复用与epoll详解&#xff1a;https://www.cnblogs.com/lojunren/p/3856290.html 彻底学会 epoll 系列&#xff1a;http://blog.chinaunix.net/uid/28541347/sid-193117-list-1.htm Linux下I/O多路复用…

Spring Data JPA 从入门到精通~AliDruidDataSource的配置

AliDruid 配置方法 &#xff08;1&#xff09;在实际工作中&#xff0c;由于 HikariCP 和 Druid 应该各有千秋&#xff0c;会发现偏向于监控&#xff0c;有很多国内开发 者使用频次最高的 AliDruid&#xff0c;我们来看看看如何配置。 <!--druid--><dependency>&…

励志演讲

王国权励志演讲&#xff08;很有激情&#xff09;转载于:https://www.cnblogs.com/Xredman/archive/2009/07/23/1529186.html

谷歌X实验室的“无用”发明

来源&#xff1a;OFweek人工智能网摘要&#xff1a;作为想要改变世界的科技界钢铁侠&#xff0c;谷歌自诞生起就发明无数。1999年&#xff0c;公司创始人拉里佩奇用导航地图开车载他同事经过一个停车场时突然想到&#xff1a;在线搜索也可以盈利。当时他认为&#xff0c;谷歌能…

php跳一跳小游戏,原生JS实现的跳一跳小游戏完整实例

本文实例讲述了原生JS实现的跳一跳小游戏。分享给大家供大家参考&#xff0c;具体如下&#xff1a;以下说的是闲暇编写的一个小游戏--跳一跳&#xff0c;类似于微信的跳一跳&#xff0c;大体实现功能有&#xff1a;1.先随机生成地图&#xff1b;2.按住按钮释放后完成动作并进行…

windows 快捷键整理

Win10快捷键大全汇总&#xff1a;http://www.pc6.com/infoview/Article_110854.html 电脑键盘快捷键和组合键功能使用大全&#xff1a;http://product.pconline.com.cn/itbk/diy/mouse/1305/3298585.html 键盘上的键都有哪些用途&#xff1a;https://www.gezila.com/tutori…

我想知道怎么求N的N次方

我想知道怎么求N的N次方&#xff0c;这个数据是很大的&#xff0c;但是我要的是这个数据的最高位的数&#xff0c;应该有什么好的方法吧&#xff01; 请大侠们帮帮忙吧&#xff01;&#xff01;&#xff08;N <1000000000&#xff09; 这个问题提出后&#xff0c;fallening同…

Google提出新型学习范式「Deep Memory」,或将彻底改变机器学习领域

图源&#xff1a;pixabay原文来源&#xff1a;arXiv作者&#xff1a;Sylvain Gelly、Karol Kurach、Marcin Michalski、Xiaohua Zhai「雷克世界」编译&#xff1a;嗯~是阿童木呀、KABUDA导语&#xff1a;最近&#xff0c;Google提出了一种称之为Deep Memory的新型学习范式&…

php内容管理器是什么原因,有什么好的php内容管理后台吗?打算试水接单的大三狗提问...

国外优秀的CMS有drupal, joomla, wordpress, typo3drupal最专业&#xff0c;扩展强大&#xff0c;但最难入门&#xff1b;wordpress最简单&#xff0c;模板多&#xff0c;但难以实现高要求&#xff1b;joomla扩展多&#xff0c;入门简单&#xff0c;但后台组织比较混乱&#xf…

网络 IPC 套接字socket

APUE书中所有实例源码下载地址&#xff1a;http://www.apuebook.com apue学习笔记&#xff08;第十六章 网络IPC&#xff1a;套接字&#xff09;&#xff1a;https://www.cnblogs.com/runnyu/p/4648678.html 一起学 Unix 环境高级编程 (APUE) 之 网络 IPC&#xff1a;套接字…

Spring Data JPA 从入门到精通~事务的处理及其讲解

默认 Transactional 注解式事务 &#xff08;1&#xff09;EnableTransactionManagement 正常情况下&#xff0c;我们是需要在 ApplicationConfig 类加上 EnableTransactionManagement 注解才能开启事务管理。通过 DataSource 的研究步骤 spring.factories 里面默认加载 Tran…

ASP.NET MVC V2 Preview 1 发布 期望VS有更好的表现

ASP.NET MVC V2 Preview 1官方首页&#xff1a;http://aspnet.codeplex.com/ 在这里可以下载 以下是网友的转载&#xff0c;介绍的还是比较详细的&#xff1a; 预览版是在.NET 3.5 SP1和VS 2008下工作的&#xff0c;可与ASP.NET MVC 1.0并行安装在同一个机器上&#xff08;即&a…

MC缓存序列化php,PHP serialize()序列化的使用

PHP serialize()序列化的使用可以将数组和对象直接存入数据库中的某一字段。使serialize()是将数组反序列化再存入数据库&#xff0c;序列化话完的数据就是一个字符串。提取的时候&#xff0c;用unserialize()反序列化取&#xff0c;取出来的还是个数组。$arr array(value1,va…

全球最权威的区块链行业报告

来源&#xff1a;腾讯研究院美国加密货币报道媒体CoinDesk近期发布“全球区块链现状报告”&#xff0c;深入研究了快速发展的加密货币行业及其底层技术&#xff0c;该报告覆盖了公共区块链、企业区块链、ICO、投资以及监管等话题&#xff0c;另外还对3000多名投资者的加密货币投…

Google 的 C++ 代码规范

Google 开源项目风格指南 (中文版)&#xff1a;https://zh-google-styleguide.readthedocs.io/en/latest/ 英文版&#xff1a;http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml 中文版&#xff1a;http://zh-google-styleguide.readthedocs.org/en/latest/goog…

解析/etc/inittab 文件(转)

原文地址&#xff1a;http://hi.baidu.com/fembed/blog/item/62a509f01b2e69aaa40f528c.htmlinit程序需要读取配置文件/etc/inittab。inittab是一个不可执行的文本文件&#xff0c;它有若干行指令所组成。在Redhat系统中&#xff0c;inittab的内容如下所示(以“###"开始的…

Spring Data JPA 从入门到精通~如何配置多数据源

如何配置多数据源 在 application.properties 中定义两个 DataSource 定义两个 DataSource 用来读取 application.properties 中的不同配置。如下例子中&#xff0c;主数据源配置为 spring.datasource.one 开头的配置&#xff0c;第二数据源配置为 spring.datasource.two 开头…

NASA投资有远景技术,有望改变未来人类和机器人的勘探任务

来源&#xff1a; 机器人创新生态据NASA官网报道&#xff0c;美国宇航局(NASA)正在投资有远见的技术概念&#xff0c;包括流星撞击探测、太空望远镜群以及细小轨道碎片测绘技术&#xff0c;这些技术将来可能被用于未来的太空探索任务中。美国宇航局已经选出25个还处于早期的技术…