暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

spring boot系列4--访问数据库

小白懂编程 2016-06-25
188

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


配置DataSource

Java的javax.sql.DataSource接口提供了一个标准的使用数据库连接的方法。传统做法是,一个DataSource使用一个URL连同相应的证书去初始化一个数据库连接。


对内嵌数据库的支持

开发应用时使用内存数据库是很实用的。显而易见地,内存数据库不需要提供持久化存储。你不需要在应用启动时填充数据库,也不需要在应用结束时丢弃数据。


Spring Boot可以自动配置的内嵌数据库包括H2, HSQL和Derby。你不需要提供任何连接URLs,只需要简单的添加你想使用的内嵌数据库依赖。


示例:典型的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被传递地拉过来了。


连接到一个生产环境数据库

在生产环境中,数据库连接可以使用DataSource池进行自动配置。下面是选取一个特定实现的算法:


由于Tomcat数据源连接池的性能和并发,在tomcat可用时,我们总是优先使用它。

如果HikariCP可用,我们将使用它。

如果Commons DBCP可用,我们将使用它,但在生产环境不推荐使用它。

最后,如果Commons DBCP2可用,我们将使用它。

如果你使用spring-boot-starter-jdbc或spring-boot-starter-data-jpa 'starter POMs',你将会自动获取对tomcat-jdbc的依赖。


DataSource配置通过外部配置文件的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

其他可选的配置可以查看DataSourceProperties。同时注意你可以通过spring.datasource.*配置任何DataSource实现相关的特定属性:具体参考你使用的连接池实现的文档。


注:既然Spring Boot能够从大多数数据库的url上推断出driver-class-name,那么你就不需要再指定它了。对于一个将要创建的DataSource连接池,我们需要能够验证Driver是否可用,所以我们会在做任何事情之前检查它。比如,如果你设置spring.datasource.driverClassName=com.mysql.jdbc.Driver,然后这个类就会被加载。


连接到一个JNDI数据库

如果正在将Spring Boot应用部署到一个应用服务器,你可能想要用应用服务器内建的特性来配置和管理你的DataSource,并使用JNDI访问它。


spring.datasource.jndi-name属性可以用来替代spring.datasource.url,spring.datasource.username和spring.datasource.password去从一个特定的JNDI路径访问DataSource。比如,下面application.properties中的片段展示了如何获取JBoss定义的DataSource:


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


使用JdbcTemplate

Spring的JdbcTemplate和NamedParameterJdbcTemplate类是被自动配置的,你可以在自己的beans中通过@Autowire直接注入它们。


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.stereotype.Component;


@Component

public class MyBean {


    private final JdbcTemplate jdbcTemplate;


    @Autowired

    public MyBean(JdbcTemplate jdbcTemplate) {

        this.jdbcTemplate = jdbcTemplate;

    }

    ...

}


JPA和Spring Data

Java持久化API是一个允许你将对象映射为关系数据库的标准技术。spring-boot-starter-data-jpa POM提供了一种快速上手的方式。它提供下列关键的依赖:


Hibernate - 一个非常流行的JPA实现。

Spring Data JPA - 让实现基于JPA的repositories更容易。

Spring ORMs - Spring框架的核心ORM支持。


实体类

传统上,JPA实体类被定义到一个persistence.xml文件中。在Spring Boot中,这个文件不是必需的,并被'实体扫描'替代。默认情况下,在你主(main)配置类(被@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;


// ... additional members, often include @OneToMany mappings


protected City() {

    no-args constructor required by JPA spec

    this one is protected since it shouldn't be used directly

}


public City(String name, String state) {

    this.name = name;

    this.country = country;

}


public String getName() {

    return this.name;

}


public String getState() {

    return this.state;

}

// ... etc

}

注:你可以使用@EntityScan注解自定义实体扫描路径。


Spring Data JPA仓库

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


对于比较复杂的查询,你可以使用Spring Data的Query来注解你的方法。


Spring Data仓库通常继承自Repository或CrudRepository接口。如果你使用自动配置,包括在你的主配置类(被@EnableAutoConfiguration或@SpringBootApplication注解的类)的包下的仓库将会被搜索。


下面是一个传统的Spring Data仓库:


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);

}


创建和删除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本身的属性,比如hibernate.hbm2ddl.auto。示例:spring.jpa.properties.hibernate.globally_quoted_identifiers=true将传递hibernate.globally_quoted_identifiers到Hibernate实体管理器。


默认情况下,DDL执行(或验证)被延迟到ApplicationContext启动。这也有一个spring.jpa.generate-ddl标识,如果Hibernate自动配置被激活,那该标识就不会被使用,因为ddl-auto设置粒度更细。


文章转载自小白懂编程,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论