In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how to configure data access in Springboot. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Custom data source configuration @ Bean @ ConfigurationProperties (prefix= "app.datasource") public DataSource dataSource () {return new FancyDataSource ();}
Configuration file
App: datasource: url: "jdbc:h3:mem:mydb" username: "sa" password: "123123" pool-size: 30
The FancyDataSource class has a corresponding url,username,pool-size property.
Spring Boot also provides a utility generator class called DataSourceBuilder that can be used to create a standard data source if it is on the classpath. The builder can detect the class to use based on what is available on the classpath. It also automatically detects drivers based on JDBCURL.
@ Bean @ ConfigurationProperties ("app.datasource") public DataSource dataSource () {return DataSourceBuilder.create () .build ();}
However, there is a trap. Because the actual type of the connection pool is not provided, no keys are generated in the metadata of the custom data source, and there is no completion available in IDE (because the data source interface does not expose any properties). In addition, if there happens to be a Hikari on the classpath, this basic setting does not work because Hikari does not have a url property (but does have a jdbcUrl property). In this case, you must rewrite the configuration as follows:
App: datasource: jdbc-url: "jdbc:mysql://localhost/test" username: "dbuser" password: "dbpass" pool-size: 30
You can force the data source type to be specified
@ Bean @ ConfigurationProperties ("app.datasource") public HikariDataSource dataSource () {return DataSourceBuilder.create () .type (HikariDataSource.class) .build ();} multiple data source configuration
If you need to configure multiple data sources, you can apply the same techniques described in the previous section. However, you must mark one of the data source instances as @ Primary, because future automatic configurations will want to get one by type.
If you create your own data source, automatic configuration exits. In the following example, we provide exactly the same feature set as the automatic configuration on the primary data source:
@ Bean @ Primary @ ConfigurationProperties ("app.datasource.first") public DataSourceProperties firstDataSourceProperties () {return new DataSourceProperties ();} @ Bean @ Primary @ ConfigurationProperties ("app.datasource.first.configuration") public HikariDataSource firstDataSource () {return firstDataSourceProperties (). InitializeDataSourceBuilder (). Type (HikariDataSource.class). Build ();} @ Bean @ ConfigurationProperties ("app.datasource.second") public BasicDataSource secondDataSource () {return DataSourceBuilder.create (). Type (BasicDataSource.class). Build ();}
The two data sources are also bound with advanced customization. For example, you can configure them as follows:
App: datasource: first: url: "jdbc:mysql://localhost/first" username: "dbuser" password: "dbpass" configuration: maximum-pool-size: 30 second: url: "jdbc:mysql://localhost/second" username: "dbuser" password: "dbpass" max-total: 30
You can also apply the same concept to secondary data sources, as shown in the following example:
@ Bean @ Primary @ ConfigurationProperties ("app.datasource.first") public DataSourceProperties firstDataSourceProperties () {return new DataSourceProperties ();} @ Bean @ Primary @ ConfigurationProperties ("app.datasource.first.configuration") public HikariDataSource firstDataSource () {return firstDataSourceProperties () .initializeDataSourceBuilder () .type (HikariDataSource.class). Build ();} @ Bean @ ConfigurationProperties ("app.datasource.second") public DataSourceProperties secondDataSourceProperties () {return new DataSourceProperties () } @ Bean @ ConfigurationProperties ("app.datasource.second.configuration") public BasicDataSource secondDataSource () {return secondDataSourceProperties () .initializeDataSourceBuilder () .type (BasicDataSource.class) .build ();} use Spring Data Repositories
Spring data can create various styles of @ Repository interface implementations. As long as these @ Repositories are contained in the same package (or subpackage) of the @ EnableAutoConfiguration class, Spring Boot can handle all of them for you.
For many applications, simply put the correct Spring Data dependency on the classpath.
Spring-boot-starter-data-jpa for JPA, spring-boot-starter-data-mongodb for Mongodb, and so on. To get started, create some repository interfaces to handle the @ Entity object.
Based on the @ EnableAutoConfiguration found, Spring Boot tries to guess the location of the @ Repository definition. For more control, use the @ EnableJpaRepositories annotation.
Separate the @ Entity definition from the Spring configuration
Spring Boot tries to guess the location defined by @ EnableAutoConfiguration based on the @ Entity it finds. For more control, you can use the @ EntityScan annotation, as shown in the following example:
@ Configuration (proxyBeanMethods = false) @ EnableAutoConfiguration @ EntityScan (basePackageClasses=City.class) public class Application {/ /...} configure the JPA property
Spring Data JPA already provides vendor-independent configuration options (such as SQL logging options), which SpringBoot exposes as external configuration properties along with some of Hibernate's options. Some of them are automatically detected based on context, so you don't have to set them.
Spring.jpa.hibernate.ddl-auto is a special case because it has different default values depending on the runtime conditions. If you use an embedded database and no schema manager, such as Liquibase or Flyway, processes the data source, it is create-drop by default. In all other cases, it defaults to none.
The dialect to be used is detected by the JPA provider. If you prefer to set your own dialect, please set
Spring.jpa.database-platform property.
Spring: jpa: hibernate: naming: physical-strategy: "com.example.MyPhysicalNamingStrategy" show-sql: true configure Hibernate naming policy
Hibernate uses two different naming strategies to map names from the object model to the corresponding database names. You can set the
The spring.jpa.hibernate.naming.physical-strategy property, whose value is the fully qualified name of the class, package + clalss.
By default, Spring Boot uses the
SpringPhysicalNamingStrategy configures a physical naming policy. This implementation provides the same table structure as Hibernate4: all points are replaced with underscores and hump cases are replaced with underscores. In addition, all table names are generated in lowercase by default. For example, a phone number entity is mapped to a phone number table. If your schema requires mixed case identifiers, define a custom SpringPhysicalNamingStrategybean, as shown in the following example:
@ Bean SpringPhysicalNamingStrategy caseSensitivePhysicalNamingStrategy () {return new SpringPhysicalNamingStrategy () {@ Override protected boolean isCaseInsensitive (JdbcEnvironment jdbcEnvironment) {return false;}};}
If you prefer to use the default settings of Hibernate 5, set the following properties:
Spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Alternatively, you can configure the following bean
Spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl configure Hibernat secondary cache
The Hibernate secondary cache can be configured for a range of cache providers. Instead of configuring Hibernate to look up the cache provider again, provide the cache provider available in the context as much as possible.
To do this using JCache, first make sure
Org.hibernate.HibernateJCache is available on the classpath. Then, add a HibernatePropertiesCustomizer bean, as shown in the following example:
@ Configuration (proxyBeanMethods = false) public class HibernateSecondLevelCacheExample {@ Bean public HibernatePropertiesCustomizer hibernateSecondLevelCacheCustomizer (JCacheCacheManager cacheManager) {return (properties)-> properties.put (ConfigSettings.CACHE_MANAGER, cacheManager.getCacheManager ());}} use multiple EntityManagerFactories
If you need to use JPA for multiple data sources, you may need one EntityManagerFactory for each data source. In Spring ORM
LocalContainerEntityManagerFactoryBean allows you to configure EntityManagerFactory as needed. You can also reuse the JPA property to bind the settings for each EntityManagerFactory, as shown in the following example:
@ Bean @ ConfigurationProperties ("app.jpa.first") public JpaProperties firstJpaProperties () {return new JpaProperties ();} @ Bean public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory (DataSource firstDataSource, JpaProperties firstJpaProperties) {EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder (firstJpaProperties); return builder.dataSource (firstDataSource) .persistence (Order.class) .persistenceUnit ("firstDs"). Build ();} private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder (JpaProperties jpaProperties) {JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter (jpaProperties); return new EntityManagerFactoryBuilder (jpaVendorAdapter, jpaProperties.getProperties (), null) } private JpaVendorAdapter createJpaVendorAdapter (JpaProperties jpaProperties) {/ / Map JPA properties as needed return new HibernateJpaVendorAdapter ();}
The above example uses the data source bean named firstDataSource to create an EntityManagerFactory. It scans entities in the same package as the order. You can use this application to map other JPA properties.
Expose Spring data repositories as REST endpoints
Spring Data Rest can expose Repository implementations as REST endpoints, as long as SpringMVC is enabled for the application.
Spring Boot exposes a useful set of attributes (from the Spring.data.rest namespace) for customization
RepositoryRestConfiguration . If you need to provide additional customization, you should use RepositoryRestConfiguration.
Use
Org.springframework.boot spring-boot-starter-data-rest org.springframework.data spring-data-rest-webmvc, thank you for your reading! This is the end of the article on "how to configure data access in Springboot". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.