SpringBoot(11) - 数据库(1)

参考文档:https://docs.spring.io/spring-boot/docs/1.5.17.RELEASE/reference/htmlsingle/#boot-features-sql

翻译的官方文档,个人理解,仅供参考。

 

Spring框架为使用SQL数据库提供了广泛的支持。从使用JdbcTemplate直接以JDBC方式访问到完全的Hibernate对象关系映射技术访问。Spring Data提供了更多级别的功能,直接从接口创建Repository实现,并使用约定从方法名称生成查询。

 

1. 配置数据源

java的javax.sql.DataSource接口提供一种使用数据库连接的标准方法。传统上,DataSource使用URL和一些凭据来建立数据库连接。

1.1 嵌入式数据库的支持

一般来说,使用内存型嵌入式数据库开发应用程序是非常方便的。很明显的,内存型数据库不需要提供持久化存储;需要在应用程序启动时填充数据库,并准备在应用程序结束时丢弃数据。

SpringBoot可以自动配置H2、HSQL和Derby嵌入式数据库。我们不需要提供任何连接的URL,仅仅需要添加想要使用的嵌入式数据库的依赖即可。

提示:如果在测试中使用此功能,整个测试过程中都会重复使用相同的数据库,无论使用的应用程序上下文的数量如何。假如想要每个上下文都有各自的嵌入式数据库,设置spring.datasource.generate-unique-name=true

示例:典型的POM依赖如下:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>runtime</scope>
</dependency>

注:

  • 一般需要依赖spring-jdbc才能自动配置嵌入式数据库。本例中spring-boot-starter-data-jpa自动添加了spring-jdbc依赖。
  • 如果由于某种原因,确实为嵌入式数据库配置了连接URL,则应注意确保禁用数据库的自动关闭。 如果使用H2,则应使用DB_CLOSE_ON_EXIT=FALSE来执行此操作。如果使用的是HSQLDB,则应确保不使用shutdown=true。 禁用数据库的自动关闭,从而确保一旦不再需要访问数据库时,Spring Boot控制数据库何时关闭。

1.2 连接到生产数据库

生产数据库可以使用数据源连接池自动配置。以下是选择特定实现的算法:

  • 优先选择Tomcat数据库连接池,因为它的性能和并发性。
  • 第二选择HikariCP
  • 第三选择DBCP,但是SpringBoot不推荐在生产环境使用
  • 第四选择DBCP2

假如使用了spring-boot-starter-jdbc或spring-boot-starter-data-jpa的starter,将会自动添加tomcat-jdbc依赖并且使用它。

提示:

  • 可以完全该算法,并通过spring.datasource.type属性指定要使用的连接池。如果在Tomcat容器中运行应用程序,则这一点尤其重要,因为默认情况下提供了tomcat-jdbc。
  • 可以手动配置其他连接池。 如果定义自己的DataSource bean,则不会进行自动配置。

数据源配置由spring.datasource.*中的外部配置属性控制。 例如,可以在application.properties中声明以下部分:

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

提示:

  • 至少应该使用spring.datasource.url属性指定url,否则Spring Boot将尝试自动配置嵌入式数据库。
  • 通常不需要指定驱动程序类名称,因为Spring可以从URL中推断出大多数数据库。
  • 对于要创建的数据库连接,SpringBoot在执行操作前检查Driver类是否可用。例如,设置spring.datasource.driver-class-name=com.mysql.jdbc.Driver,那么该类必须是可加载的。

查看DataSourceProperties获取更多选项。这些是标准的选项,不论实际的实现是什么。也可以使用各自的前缀(spring.datasource.tomcat.*,spring.datasource.hikari.*和spring.datasource.dbcp2.*)来微调特定实现的设置。

例如,如果使用的是Tomcat连接池,则可以自定义许多其他设置:

# 如果没有可用的连接,则在抛出异常之前要等待的ms数
spring.datasource.tomcat.max-wait=10000

# 可以同时从此池分配的最大活动连接数
spring.datasource.tomcat.max-active=50

# 在从池中获取连接之前验证连接
spring.datasource.tomcat.test-on-borrow=true

1.3 连接到JNDI数据源

如果要将Spring Boot应用程序部署到Application Server,则可能需要使用Application Server内置功能配置和管理DataSource,并使用JNDI访问它。

spring.datasource.jndi-name属性可用作spring.datasource.url,spring.datasource.username和spring.datasource.password属性的替代,以从特定JNDI位置访问DataSource。 例如,application.properties中的以下部分显示了如何访问JBoss AS定义的数据源:

spring.datasource.jndi-name=java:jboss/datasources/customers

 

2. 使用JdbcTemplate

Spring的JdbcTemplate和NamedParameterJdbcTemplate类被自动配置,可以在自己的bean中通过@Autowire注解直接使用。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class MyBean {
    @Autowired
    private JdbcTemplate jdbcTemplate;
}

 

3. JPA和'Spring Data'

Java Persistence API(JPA)是一种标准技术,允许将对象“映射”到关系数据库。spring-boot-starter-data-jpa POM提供一种快速开始的方式。它提供了以下关键的依赖:

  • Hibernate:最流行的JPA实现之一
  • Spring Data JPA:使实现基于JPA的存储库变得容易
  • Spring ORMS:Spring框架提供的核心ORM支持

提示:默认SpringBoot使用Hibernate5.0.x,也可以使用4.3.x or 5.2.x 。具体可以参考Hibernate4和Hibernate5.2的demo。

3.1 实体类

传统上,JPA“实体”类在persistence.xml文件中指定。 使用Spring Boot,此文件不是必需的,而是使用“实体扫描”。 默认情况下,将搜索主配置类下面的所有包(使用@EnableAutoConfiguration或@SpringBootApplication注释的包)。

任何使用@Entity,@Embeddable或@MappedSuperclass注释的类都将被考虑。 典型的实体类看起来像这样:

package com.example.myapp.domain;

import java.io.Serializable;
import javax.persistence.*;

@Entity
public class City implements Serializable {
    @Id
    @GeneratedValue
    private Long id;
    @Column(nullable = false)
    private String name;
    @Column(nullable = false)
    private String state;

    // 其他成员属性,通常包括@OneToMany映射
    protected City() {
        // JPA规范要求无参构造器,应该是protected,因为它不应该直接使用
    }
    public City(String name, String state) {
        this.name = name;
        this.country = country;
    }
    public String getName() {
        return this.name;
    }
    public String getState() {
        return this.state;
    }
    // ...
}

可以使用@EntityScan注释自定义实体扫描位置。

3.2 Spring Data JPA Repositories

Spring Data JPA Repositories是可以定义以访问数据的接口。 JPA查询是根据方法名称自动创建的。 例如,CityRepository接口可能会声明一个findAllByState(String state)方法来查找给定状态中的所有城市。

对于更复杂的查询,可以使用Spring Data Query注解对方法进行注释。

Spring Data repositories 通常从Repository或CrudRepository接口扩展。 如果使用自动配置,则将从包含主配置类(使用@EnableAutoConfiguration或@SpringBootApplication注解的)的包中搜索。

下面是典型的Spring Data repository:

package com.example.myapp.domain;

import org.springframework.data.domain.*;
import org.springframework.data.repository.*;

public interface CityRepository extends Repository<City, Long> {
    Page<City> findAll(Pageable pageable);
    City findByNameAndCountryAllIgnoringCase(String name, String country);
}

3.3 创建和删除JPA数据库

默认情况下,仅当使用嵌入式数据库(H2,HSQL或Derby)时,才会自动创建JPA数据库。 可以使用spring.jpa.*属性显式配置JPA设置。 例如,要创建和删除表,可以将以下内容添加到application.properties中:

spring.jpa.hibernate.ddl-auto=create-drop

注:Hibernate自己的内部属性名称是hibernate.hbm2ddl.auto。 可以使用spring.jpa.properties.*(在将它们添加到实体管理器之前剥离前缀)来设置它以及其他Hibernate本机属性。 例:

spring.jpa.properties.hibernate.globally_quoted_identifiers=true

将hibernate.globally_quoted_identifiers传递给Hibernate实体管理器。

默认情况下,DDL执行(或校验)将延迟到ApplicationContext启动。 还有一个spring.jpa.generate-ddl标志,但如果Hibernate autoconfig处于活动状态,则不会使用它,因为ddl-auto设置更精细。

3.4 Open EntityManager in View

如果正在运行Web应用程序,Spring Boot将默认注册OpenEntityManagerInViewInterceptor以应用“Open EntityManager in View”模式,即允许在Web视图中进行延迟加载。 如果不想要此行为,则应在application.properties中将spring.jpa.open-in-view设置为false。

 

4. 使用H2的web控制台

H2数据库提供了一个基于浏览器的控制台,Spring Boot可以为您自动配置。 满足以下条件时,将自动配置控制台:

  • 开发一个web应用程序
  • com.h2database:h2在classpath下
  • 使用SpringBoot的developer tools

注:如果没有使用Spring Boot的developer tools,但仍想使用H2的控制台,那么可以通过配置spring.h2.console.enabled=true属性来实现。H2控制台仅用于开发期间,因此应注意确保spring.h2.console.enabled在生产中未设置为true。

4.1 改变H2控制台的路径

默认情况下,控制台将在/h2-console上可用。可以使用spring.h2.console.path属性自定义控制台的路径。

4.2 确保H2控制台的安全

当Spring Security在类路径上并启用基本身份验证时,H2控制台将使用基本身份验证自动保护。 以下属性可用于自定义安全性配置:

  • security.user.role
  • security.basic.authorize-mode
  • security.basic.enabled

 

5. 使用jOOQ

Java面向对象查询(jOOQ)是Data Geekery的一个流行产品,它从您的数据库生成Java代码,并允许您通过其流畅的API构建类型安全的SQL查询。 商业版和开源版都可以与Spring Boot一起使用。

5.1 代码生成

要使用jOOQ类型安全查询,需要从数据库模式生成Java类。 可以按照jOOQ用户手册中的说明进行操作。 如果您使用的是jooq-codegen-maven插件(并且还使用了spring-boot-starter-parent“父POM”),则可以安全地省略插件的<version>标记。 还可以使用Spring Boot定义的版本变量(例如h2.version)来声明插件的数据库依赖性。 这是一个例子:

<plugin>
    <groupId>org.jooq</groupId>
    <artifactId>jooq-codegen-maven</artifactId>
    <executions>
        ...
    </executions>
    <dependencies>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>${h2.version}</version>
        </dependency>
    </dependencies>
    <configuration>
        <jdbc>
            <driver>org.h2.Driver</driver>
            <url>jdbc:h2:~/yourdatabase</url>
        </jdbc>
        <generator>
            ...
        </generator>
    </configuration>
</plugin>

5.2 使用DSLContext

jOOQ提供的流畅API通过org.jooq.DSLContext接口启动。 Spring Boot会将DSLContext自动配置为Spring Bean并将其连接到应用程序DataSource。 要使用DSLContext,只需@Autowire:

@Component
public class JooqExample implements CommandLineRunner {
    private final DSLContext create;
    @Autowired
    public JooqExample(DSLContext dslContext) {
        this.create = dslContext;
    }
}

然后可以使用DSLContext构建查询:

public List<GregorianCalendar> authorsBornAfter1980() {
    return this.create.selectFrom(AUTHOR)
        .where(AUTHOR.DATE_OF_BIRTH.greaterThan(new GregorianCalendar(1980, 0, 1)))
        .fetch(AUTHOR.DATE_OF_BIRTH);
}

5.3 自定义jOOQ

可以通过在application.properties中设置spring.jooq.sql-dialect来自定义jOOQ使用的SQL方言。 例如,要指定Postgres,需要添加:

spring.jooq.sql-dialect=Postgres

通过定义自己的@Bean定义可以实现更高级的自定义,这些定义将在创建jOOQ配置时使用。 可以为以下jOOQ类型定义bean:

  • ConnectionProvider
  • TransactionProvider
  • RecordMapperProvider
  • RecordListenerProvider
  • ExecuteListenerProvider
  • VisitListenerProvider

如果要完全控制jOOQ配置,还可以创建自己的org.jooq.Configuration @Bean。

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值