官术网_书友最值得收藏!

How it works...

Even though, by default, Spring Boot makes certain assumptions about the database configuration by examining the classpath for the presence of supported database drivers, it provides you with easy configuration options to tweak the database access via a set of exposed properties grouped under spring.datasource.

The things that we can configure are url, username, password, driver-class-name, and so on. If you want to consume the datasource from a JNDI location, where an outside container creates it, you can configure this using the spring.datasource.jndi-name property. The complete set of possible properties is fairly large, so we will not go into all of them. However, we will cover more options in Chapter 5, Application Testing, where we will talk about mocking data for application tests using a database.

By looking at various blogs and examples, you may notice that some places use dashes in property names like driver-class-name, while others use camel-cased variants:  driverClassName. In Spring Boot, these are actually two equally supported ways of naming the same property, and they get translated into the same thing internally.

If you want to connect to a regular (non-embedded) database, besides just having the appropriate driver library in the classpath, we need to specify the driver of our choice in the configuration. The following code snippet is what the configuration to connect to MySQL would resemble:

    spring.datasource.driver-class-name: com.mysql.jdbc.Driver
    spring.datasource.url:   
jdbc:mysql://localhost:3306/springbootcookbook
spring.datasource.username: root spring.datasource.password:

If we wanted Hibernate to create the schema automatically, based on our entity classes, we would need to add the following line to the configuration:

    spring.jpa.hibernate.ddl-auto=create-drop
  
Don't do it in the production environment, otherwise, on startup, all the table schemas and data will be deleted! Use the update or validate values instead, where needed.

You can go even further in the abstraction layer and, instead of autowiring a DataSource object, you could go straight for  JdbcTemplate. This would instruct Spring Boot to automatically create a DataSource and then create a JdbcTemplate wrapping the datasource, thus providing you with a more convenient way of interacting with a database in a safe way. The code for JdbcTemplate is as follows:

@Autowired 
private JdbcTemplate jdbcTemplate; 

You can also look in the spring-boot-autoconfigure source at an org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration file to see the code behind the datasource creation magic.

主站蜘蛛池模板: 儋州市| 东明县| 拉萨市| 临泽县| 宝鸡市| 福鼎市| 察雅县| 宜春市| 仁怀市| 芜湖县| 安顺市| 尼勒克县| 广州市| 华亭县| 长丰县| 尉犁县| 灵璧县| 志丹县| 建德市| 荣昌县| 孝昌县| 宿州市| 南昌县| 浦城县| 理塘县| 尉犁县| 化隆| 望奎县| 灵山县| 黄冈市| 安远县| 西乌珠穆沁旗| 泾川县| 防城港市| 邵武市| 油尖旺区| 长岛县| 综艺| 武隆县| 呼玛县| 洪雅县|