Spring – druid + jpa + tx boot integration

jpa

Jpa introduction

java persistence API

Is a Java persistence specification with two main objectives:

  1. forjavaThe application developer provideso/r mappingTools to managejavaRelational data in applications simplifies the task of developing persistence.
  2. Integrate ORM technology. Projects such as Hibernate (version 3.2) and TopLink Essentials have implemented the Java Persistence API specification.

Hibernate

  • Hibernate provides an open source object-relational mapping framework for Java

  • Gavin King founded the Hibernate project.

  • Hibernate development team joined JBoss.

  • Version 3.2 and later provide implementations of Java persistence apis.

spring data

Spring Data is an open source framework for simplifying database access and enabling cloud services.

Provides relatively consistent storage while preserving the underlying storage features. Spring-based programming model.

Main modules:

  • Spring data jdbc
  • spring data jpa
  • spring data redis
  • spring data mongodb
  • spring data keyvalue
  • .

spring-boot-starter-data-jpa

Defining entity Objects

/ / parent class
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Data
public abstract class BaseEntity implements Serializable {

  @Column(name = "create_time", updatable = false)
  @CreationTimestamp
  private Date createTime;

  /** last updated */
  @Column(name = "update_time")
  @UpdateTimestamp
  private Date updateTime;
}
Copy the code
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "T_MENU")
public class Menu extends BaseEntity {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long menuId;

  @Column(name = "parent_id")
  private Long parentId;

  private String name;

  private String url;

  private Integer type;

  @Column(name = "order_num")
  private Integer orderNum;

  @Column(name = "is_deleted")
  private int isDeleted;
}
Copy the code

Common notes:

Entity: marks this class as an Entity bean

@table: Used to configure the mapping between a Table and a class

@column: specifies details about the mapping between a Column and a field or attribute. The most commonly used attribute is:

  • The name attribute allows you to explicitly specify the name of a column.
  • The length attribute is the size of the column used to map a value, especially a string value.
  • The Nullable attribute allows a column to be marked as non-empty when a schema is generated.
  • The unique attribute allows columns to contain only one content
  • Whether the updatable property can be modified

@ Id: the primary key

@generatedValue: Primary key generation policy

  • TABLE: Uses a specific database TABLE to hold the primary key.
  • SEQUENCE: Generates primary keys based on the SEQUENCE of the underlying database, provided that the database supports sequences.
    • @sequenceGenerator: Specifies the sequence name
  • IDENTITY: Primary key generated automatically by the database (mainly auto-growing)
  • AUTO: The primary key is controlled by the program.

@creationtimestamp: creation time

@updatetimestamp: indicates the update time

@OrderBy

The following are comments on the relationships between tables

1 to 1, 1 to many, many to 1, many to many

inheritance

@JoinTable

@JoinColumn

@OneToOne

@OneToMany

@ManyToOne

@ManyToMany

@MappedSuperclass

@EntityListeners(AuditingEntityListener.class)

Repository

@EnableJpaRepositories

@NoRepositoryBean

Interface:

PagingAndSortingRepository<T, ID>

CrudRepository<T, ID>

JpaRepository<T, ID>

Method definition

  • Query method definition

    find.. By... / get... By... / query... By... / read... By...

  • Definition of statistical method

    count... By...

  • Sorting method definition

    ...OrderBy...[Asc/Desc]

  • Conditions for joining together

Keyword Sample JPQL snippet
And findByLastnameAndFirstname … where x.lastname = ? 1 and x.firstname = ? 2
Or findByLastnameOrFirstname … where x.lastname = ? 1 or x.firstname = ? 2
Is,Equals findByFirstnameIs,findByFirstnameEquals … where x.firstname = ? 1
Between findByStartDateBetween … where x.startDate between ? 1 and ? 2
LessThan findByAgeLessThan … where x.age < ? 1
LessThanEqual findByAgeLessThanEqual … Where x.a ge ⇐? 1
GreaterThan findByAgeGreaterThan … where x.age > ? 1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ? 1
After findByStartDateAfter … where x.startDate > ? 1
Before findByStartDateBefore … where x.startDate < ? 1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ? 1
NotLike findByFirstnameNotLike … where x.firstname not like ? 1
StartingWith findByFirstnameStartingWith … where x.firstname like ? 1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ? 1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ? 1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ? 1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ? 1
In findByAgeIn(Collection ages) … where x.age in ? 1
NotIn findByAgeNotIn(Collection age) … where x.age not in ? 1
TRUE findByActiveTrue() … where x.active = true
FALSE findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(? 1)
  • paging

    Pageable/Sort/Slice/Page

  • The rest of the

    Top/Distinct/First

@NoRepositoryBean
public interface BaseRepository<T.Long> extends PagingAndSortingRepository<T.Long> {}
Copy the code
public interface MenuRepository extends BaseRepository<Menu.Long> {}
Copy the code

druid

Druid is the best database connection pool in the Java language. Druid provides powerful monitoring and extension capabilities.

druid.wiki

spring.datasource.url: JDBC: mysql: / / 127.0.0.1:3306 / spring - the boot - demo? useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
spring.datasource.username: root
spring.datasource.password: Gepoint
spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver
spring.datasource.type: com.alibaba.druid.pool.DruidDataSource ## Specifies the connection pool. The default is Hikari

spring.datasource.druid.initial-size: 5
spring.datasource.druid.max-active: 5
spring.datasource.druid.min-idle: 5
spring.datasource.druid.max-wait: 60000
spring.datasource.druid.filters: conn,config,stat,slf4j
spring.datasource.druid.test-on-borrow: true
spring.datasource.druid.test-on-return: true
spring.datasource.druid.test-while-idle: true
Copy the code

transaction

Spring Transaction Propagation features

disseminated value describe
PROPAGATION_REQUIRED 0 If no outer transaction exists, actively create a transaction; Otherwise, use outer transactions
PROPAGATION_SUPPORTS 1 If no outer transaction exists, the transaction is not started; Otherwise, use outer transactions
PROPAGATION_MANDATORY 2 If no outer transaction exists, an exception is thrown; Otherwise, use outer transactions
PROPAGATION_REQUIRES_NEW 3 Always initiate transactions; If there are outer transactions, suspend them
PROPAGATION_NOT_SUPPORTED 4 Always do not open transactions; If there are outer transactions, suspend them
PROPAGATION_NEVER 5 Always do not open transactions; If an outer transaction exists, an exception is thrown
PROPAGATION_NESTED 6 If no outer transaction exists, actively create a transaction; Otherwise, create nested subtransactions

Spring Transaction Core interface

  • PlatformTransactionManager
    • DataSourceTransactionManager
    • HibernateTransactionManager
    • JtaTransactionManager
  • TransactionDefinition
    • Propagation
    • Isolation
    • Timeout
    • Read-only Status

One of two ways

  1. Declarative transaction

    @EnableTransactionManagement(proxyTargetClass,mode,order)

    @Transactional(transactionManager,propagation,isolation,timeout,readOnly,rollbackFor)

  2. Programmatic transactions:

    • TransactionTemplate

      TransactionCallback

      TransactionCallbackWithoutResult

    • PlatformTransactionManager

      TransactionDefinition

    @Autowired
    private TransactionTemplate txTemplate;
    
    @Autowired
    private JdbcTemplate template;
    
    txTemplate.execute(status->{
        template.execute("insert into t (id) values (1)");
        status.setRollbackOnly();
    })
    Copy the code

    [Example code](gitee.com/shawn_fight…

)