Spring Data JPA 与 Spring Boot

1. Spring Boot common CI

Based on Spring Boot 2.0.6.RELEASE

1.1 Configuration attribute class

spring.jpaRelated items prefix defined in JpaPropertiesthe class,

1.2 Automatic Assembly type

Category involves automatic configuration comprising: JpaBaseConfiguration,HibernateJpaAutoConfiguration

1.3 Common Configuration Item

# 是否开启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 configuration items spring.jpa.database

CI spring.jpa.databasevalues typically can be automatically detected, possible values include:

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

1.5 CI spring.jpa.generate-ddl and spring.jpa.hibernate.ddl-auto

Configuration item spring.jpa.generate-ddlmanagement is turned on automatically initialized Schema properties,

CI spring.jpa.hibernate.ddl-autofurther control characteristic Schema start initialization, the following possible values:

  1. create, Delete a table generated at startup, and according to the entity class generation table, the data table will be empty;
  2. create-dropWhen starting to generate the table based on the entity class, sessionFactorydeleting the table when closed;
  3. update, According to the entity class start-table, when the attributes of the entity changes, will update the table structure, the development stage can use this property;
  4. validate, The verification entity classes and data tables are the same when you start, you can take this option if the data structure is stable;
  5. noneDo not take any action;

2. Develop Common Notes - Table / Entity classes use

2.1 @Entity

@EntityUsed in entity class, which is represented by an entity class and mapping database table.

2.2 @Table

@TableClass is used to declare table information corresponding to the entity. Including table name, indexes, and so on.

2.3 @SQLDelete,@Where

@SQLDeleteDeleted from the statement by definition, @Whereis used to specify the condition.

If you do not want to use JPA Repository comes with the delete statement, you can use the annotation rewritten, such as the common soft-deleted:

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

2.4 @MappedSuperclass

@MappedSuperclassTable is used to define a number of common fields, they are packaged in a base class, the base class using the annotation, it will automatically receive fruiting body class field mapping between the parent class, a parent class at the same time no additional establishment the real table, which is the only real table corresponding to @MappedSuperclassthe subclass.

E.g:

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

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

2.5 @Inheritance

@MappedSuperclassIt specifies that there can be a hierarchical relationship between the entity classes, through @Inheritancefurther hierarchical relationship management, its value InheritanceTypehas the following enumeration:

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. Develop Common notes - Field / field use

3.1 @Column

@ColumnA field declaration table mapping the domain / methods, which may further specify whether the attribute may be NULL, and other details are unique.

3.2 @Id

@IdA label attribute, indicating that the primary key attribute map database.

3.3 @GeneratedValue

@GeneratedValueSet automatic generation field.

Its strategyproperty value of an enumeration 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

After Oracle 12c support Identity Column (identity column), can be used GenerationType.IDENTITYas a generation strategy, no longer need to use this time @SequenceGeneratorto specify a corresponding sequence. Prior to Oracle generally used to achieve the self-energizing field sequence, it is necessary to specify generation strategy GenerationType.SEQUENCEand with @SequenceGeneratorthe use of (below).

Oracle 12c using the new Identity Column Please read: https://www.cnblogs.com/zyon/p/11067115.html

@GeneratedValue#generatorProperty specifies the name of the primary key generator, needs @SequenceGeneratoror TableGeneratorassociation name.

3.4 @SequenceGenerator

If the primary key generated using the sequence mode, @SequenceGeneratorthe specified sequence (Sequence) corresponding to the primary key automatically generated.

  • @SequenceGenerator#nameSpecifies the name of the sequence generator, @GeneratedValue#generatorby the reference value associated with a specific sequence generator, in turn associated with specific sequences.
  • @SequenceGenerator#sequenceNameSpecify the physical sequence name automatically generated when the primary key;
  • @SequenceGenerator#initialValueProperty specifies the sequence of the initial value;
  • @SequenceGenerator#allocationSizeSpecified increment step size;

Example:

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

4. Common Repository

4.1 Repository

public interface Repository<T, ID>

The most basic Repository interface does not provide any method of operation.

4.2 CrudRepository

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

Providing basic CRUD operations Interface Repository.

4.3 PagingAndSortingRepository

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

It inherits CrudRepositorythe interface in CrudRepositorytwo new methods and paging-related basis.

May not be directly inherited from the persistence layer interface definition PagingAndSortingRepository, but the succession Repository, or CrudRepositoryon the basis of the method defined in the parameter list from the last addition of one Pageableor a Sorttype of parameter to specify the ordering information or paging may be implemented directly than inheritance PagingAndSortingRepositorygreater flexibility.

4.4 JpaRepository

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

JpaRepositoryInheritance PagingAndSortingRepositoryis an interface for JPA technology provided it on the basis of the parent interface provides a number of other methods, such as flush(), saveAndFlush(), deleteInBatch()and so on.

reference:

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

Guess you like

Origin www.cnblogs.com/zyon/p/11054889.html