Spring Data JPA 与 Spring Boot

1. Spring Boot常用配置项

基于Spring Boot 2.0.6.RELEASE

1.1 配置属性类

spring.jpa前缀的相关配置项定义在JpaProperties类中,

1.2 自动装配类

涉及到的自动配置类包括:JpaBaseConfigurationHibernateJpaAutoConfiguration

1.3 常用配置项

# 是否开启JPA Repositories,缺省: true
spring.data.jpa.repositories.enabled=true

# JPA数据库类型,默认可以自动检测,也能通过设置spring.jpa.database-platform达到同样效果
spring.jpa.database=ORACLE

# 数据库平台,常见的值如:
# org.hibernate.dialect.Oracle10gDialect
# org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect

# 是否使用JPA初始化数据库,可以在启动时生成DDL创建数据库表,缺省为false
spring.jpa.generate-ddl = false

# 更细粒度的控制JPA初始化数据库特性,用来设定启动时DDL操作的类型,下文有详细介绍
# 内嵌数据库 hsqldb, h2, derby的缺省值为create-drop
# 非内嵌数据库的缺省值为none
spring.jpa.hibernate.ddl-auto = update

# Hibernate操作时显示真实的SQL
spring.jpa.show-sql = true

# Hibernate 5 隐含命名策略类的全限定名
spring.jpa.hibernate.naming.implicit-strategy= 

# Hibernate 5 物理命名策略类的全限定名
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl 

# Use Hibernate's newer IdentifierGenerator for AUTO, TABLE and SEQUENCE.
spring.jpa.hibernate.use-new-id-generator-mappings= 

# 额外设置JPA配置属性,通常配置项是特定实现支持的,如下面的一条配置项
spring.jpa.properties.* = 

# 将SQL中的标识符(表名,列名等)全部使用双引号括起来
spring.jpa.properties.hibernate.globally_quoted_identifiers=true

# 将SQL中的标识符(表名,列名等)全部使用双引号括起来
spring.jpa.hibernate.globally_quoted_identifiers=true

# Register OpenEntityManagerInViewInterceptor. Binds a JPA EntityManager to the thread for the entire processing of the request.
spring.jpa.open-in-view=true

# Hibernate 4 命名策略的全类名,Hibernate 5不再适用
spring.jpa.hibernate.naming-strategy=

1.4 配置项 spring.jpa.database

配置项spring.jpa.database的值通常可以自动检测,可取值包括了:

public enum Database {
    DEFAULT,
    DB2,
    DERBY,
    H2,
    HSQL,
    INFORMIX,
    MYSQL,
    ORACLE,
    POSTGRESQL,
    SQL_SERVER,
    SYBASE
}

1.5 配置项spring.jpa.generate-ddl 和 spring.jpa.hibernate.ddl-auto

配置项spring.jpa.generate-ddl管理是否开启自动初始化Schema特性,

配置项spring.jpa.hibernate.ddl-auto进一步控制启动时初始化Schema的特性,有以下可选值:

  1. create, 启动时删除上一次生成的表,并根据实体类生成表,表中的数据将被清空;
  2. create-drop,启动时根据实体类生成表,sessionFactory关闭时删除表;
  3. update,启动时根据实体类生成表,当实体的属性变动时,表结构也会更新,开发阶段可以使用该属性;
  4. validate,启动时验证实体类和数据表是否一致,在数据结构稳定时可以采取该选项;
  5. none,不采取任何操作;

2. 开发常用注解——表/实体类使用

2.1 @Entity

@Entity用在实体类上,表示这是一个和数据库表映射的实体类。

2.2 @Table

@Table用来声明实体类对应的表信息。包括表名称、索引等。

2.3 @SQLDelete,@Where

@SQLDelete用来自定义删除语句,@Where用来指定条件。

如果不想使用JPA Repository自带的删除语句,就可以使用该注解重写,如常见的软删除:

@Entity
@Table(name = "App")
@SQLDelete(sql = "Update App set isDeleted = 1 where id = ?")
@Where(clause = "isDeleted = 0")

2.4 @MappedSuperclass

@MappedSuperclass用来定义若干表中公共的字段,将它们封装在一个基类中,基类上使用该注解,则其子实体类将自动获得父类中的字段映射关系,同时不需要额外为父类建立真实的表,也就是真正的表只对应@MappedSuperclass的子类。

例如:

@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BaseEntity 

@Entity
@Table(name="App")
public class AppEntity entends BaseEntity

2.5 @Inheritance

@MappedSuperclass指定了实体类之间是可以存在层次关系的,通过@Inheritance可以进一步管理层次关系,其取值InheritanceType有以下枚举变量:

public enum InheritanceType {

    /** A single table per class hierarchy. */
    SINGLE_TABLE,

    /** A table per concrete entity class. */
    TABLE_PER_CLASS,

    /**
     * A strategy in which fields that are specific to a
     * subclass are mapped to a separate table than the fields
     * that are common to the parent class, and a join is
     * performed to instantiate the subclass.
     */
    JOINED
}

3. 开发常用注解——字段/域使用

3.1 @Column

@Column声明一个表字段与域/方法的映射,其属性可以进一步指定是否可为NULL,是否唯一等细节。

3.2 @Id

@Id标注一个属性,表示该属性映射为数据库的主键。

3.3 @GeneratedValue

@GeneratedValue设置字段的自动生成方式。

strategy属性取值为枚举GenerationType

    /**
     * Indicates that the persistence provider must assign
     * primary keys for the entity using an underlying
     * database table to ensure uniqueness.
     */
    TABLE,

    /**
     * Indicates that the persistence provider must assign
     * primary keys for the entity using a database sequence.
     */
    SEQUENCE,

    /**
     * Indicates that the persistence provider must assign
     * primary keys for the entity using a database identity column.
     */
    IDENTITY,

    /**
     * Indicates that the persistence provider should pick an
     * appropriate strategy for the particular database. The
     * <code>AUTO</code> generation strategy may expect a database
     * resource to exist, or it may attempt to create one. A vendor
     * may provide documentation on how to create such resources
     * in the event that it does not support schema generation
     * or cannot create the schema resource at runtime.
     */
    AUTO

Oracle 12c以后支持Identity Column(身份列),可以使用GenerationType.IDENTITY作为生成策略,此时无需再使用@SequenceGenerator指定对应序列。此前的Oracle通常使用序列实现自增字段,需要将生成策略指定为GenerationType.SEQUENCE并配合@SequenceGenerator(下文)使用。

Oracle 12c新增Identity Column的使用请阅读:https://www.cnblogs.com/zyon/p/11067115.html

@GeneratedValue#generator属性指定主键生成器的名称,需要与@SequenceGeneratorTableGenerator的名称对应起来。

3.4 @SequenceGenerator

如果使用序列方式生成主键,@SequenceGenerator指定自动生成主键时对应的序列(Sequence)。

  • @SequenceGenerator#name指定序列生成器的名称,@GeneratedValue#generator通过引用该值与具体的序列生成器关联,进而关联具体的序列。
  • @SequenceGenerator#sequenceName指定自动生成主键时的物理序列名称;
  • @SequenceGenerator#initialValue属性指定序列初值;
  • @SequenceGenerator#allocationSize指定自增步长;

实例:

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
  @SequenceGenerator(name = "sequence", sequenceName = "ID_SEQ", allocationSize = 1)
  @Column(name = "Id")
  private long id;

4. 常用Repository

4.1 Repository

public interface Repository<T, ID>

最基础的Repository接口,不提供任何操作方法。

4.2 CrudRepository

public interface CrudRepository<T, ID> extends Repository<T, ID>

提供CRUD基本操作的Repository接口。

4.3 PagingAndSortingRepository

public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID>

它继承 CrudRepository 接口,在 CrudRepository 基础上新增了两个与分页有关的方法。

也可以不将自定义的持久层接口直接继承PagingAndSortingRepository,而是继承 RepositoryCrudRepository 的基础上,在自定义方法参数列表最后增加一个 PageableSort 类型的参数,用于指定分页或排序信息,可以实现比直接继承 PagingAndSortingRepository 更大的灵活性。

4.4 JpaRepository

public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T>

JpaRepository 继承PagingAndSortingRepository,是针对 JPA 技术提供的接口,它在父接口的基础上,提供了其他一些方法,比如flush()saveAndFlush()deleteInBatch() 等。

参考:

https://www.jianshu.com/p/c14640b63653

猜你喜欢

转载自www.cnblogs.com/zyon/p/11054889.html