使用JdbcTemplate
Spring的JdbcTemplate和NamedParameterJdbcTemplate类会被自动配置,你可以将它们直接@Autowire到自己的beans:
JPA和Spring Data
Java持久化API是一个允许你将对象映射为关系数据库的标准技术,spring-boot-starter-data-jpa POM提供了一种快速上手的方式,它提供以下关键依赖:
Hibernate – 一个非常流行的JPA实现。
Spring Data JPA – 让实现基于JPA的repositories更容易。
Spring ORMs – Spring框架支持的核心ORM。
注意
这里不会涉及太多关于JPA或Spring Data的细节。你可以参考来自spring.io的指南使用JPA获取数据,并阅读Spring Data JPA和Hibernate的参考文档。
注意
Spring Boot默认使用Hibernate 5.0.x,如果你希望的话也可以使用4.3.x或5.2.x,具体参考Hibernate 4和Hibernate 5.2示例。
实体类
通常,JPA实体类被定义到一个persistence.xml文件,在Spring Boot中,这个文件被’实体扫描’取代。默认情况,Spring Boot会查找主配置类(被@EnableAutoConfiguration或@SpringBootApplication注解的类)下的所有包。
任何被@Entity,@Embeddable或@MappedSuperclass注解的类都将被考虑,一个普通的实体类看起来像这样:
注意
你可以使用@EntityScan注解自定义实体扫描路径。
Spring Data JPA仓库
Spring Data JPA仓库(repositories)是用来定义访问数据的接口。根据你的方法名,JPA查询会被自动创建,比如,一个CityRepository接口可能声明一个findAllByState(String state)方法,用来查找给定状态的所有城市。
对于比较复杂的查询,你可以使用Spring Data的Query注解你的方法。
+
Spring Data仓库通常继承自Repository或CrudRepository接口。如果你使用自动配置,Spring Boot会搜索主配置类(注解@EnableAutoConfiguration或@SpringBootApplication的类)所在包下的仓库。
下面是典型的Spring Data仓库:
注意
我们仅仅触及了Spring Data JPA的表面,具体查看它的参考指南。
默认情况下,只有在你使用内嵌数据库(H2, HSQL或Derby)时,JPA数据库才会被自动创建。你可以使用spring.jpa.*属性显式的设置JPA,比如,将以下配置添加到application.properties中可以创建和删除表:
注意
Hibernate自己内部对创建,删除表支持的属性是hibernate.hbm2ddl.auto(如果你记得更好)。你可以使用spring.jpa.properties.*(前缀在被添加到实体管理器之前会被去掉)设置Hibernate其他的native属性,比如:spring.jpa.properties.hibernate.globally_quoted_identifiers=true将传递hibernate.globally_quoted_identifiers到Hibernate实体管理器。
通常,DDL执行(或验证)被延迟到ApplicationContext启动后,这可以通过spring.jpa.generate-ddl标签控制,如果Hibernate自动配置被激活,那该标识就不会被使用,因为ddl-auto设置粒度更细。