Spring – data – jpa SpringBoot integration

Jpa is a specification defined by JavaEE. The commonly used implementation is Hibernate, while spring-data-jpa is another layer of encapsulation of jpa, providing more convenient methods.

I’m not going to go into the use of Spring-data-JPA, but I’m just going to show you how to integrate it quickly, for those of you who want to learn, but keep getting stuck, right

Import dependence

<dependency>
	<groupId>com.zaxxer</groupId>
	<artifactId>HikariCP</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Copy the code

configuration

spring:
  data:
    jpa:
      repositories:
        # open jpa
        enabled: true
        bootstrap-mode: default
  jpa:
    # database dialect
    database-platform: org.hibernate.dialect.MySQL57Dialect
    open-in-view: false
    # print SQL
    show-sql: false
    properties:
      Format the output SQL statement
      hibernate.format_sql: false
    hibernate:
      Automatic table creation policy
      ddl-auto: update
Copy the code

The configuration of the data source is ignored

About the automatic table building policy

# enumeration valuesSpring.jpa.hibernate. DDL -auto create Creates a new table at startup regardless of whether the table exists or not (resulting in data loss). Create-drop Creates a table at startup. Select * from SessionFactory; delete from SessionFactory; none Delete from SessionFactory; none Delete from SessionFactory; update Create a table if it does not exist;Copy the code

Related configuration classes

This section only lists some common configurations. You can refer to configuration classes for all configuration information

  • JpaProperties (spring.jpa)
  • SpringDataWebProperties (spring.data.web)
  • HibernateProperties (spring.jpa.hibernate)

IO /spring-boot…

Defining entity Classes

User

import java.io.Serializable;
import java.time.LocalDateTime;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.Table;

// Specify the table name
@Table(name = "user", indexes = {
	// Define the index
	@Index(columnList = "account", unique = true)})// Identify the entity class
@Entity
// Set table comments
@org.hibernate.annotations.Table(appliesTo = "user", comment = "User")
public class User implements Serializable {

	/ * * * * /
	private static final long serialVersionUID = 4953012795378725917L;

	@Id / / id field
	@Column(columnDefinition = "INT(11) UNSIGNED COMMENT 'id'")
	@GeneratedValue(strategy = GenerationType.IDENTITY) / / since the increase
	private Integer id;

	/ / account
	@Column(columnDefinition = "VARCHAR(50) COMMENT 'login '", nullable = false)
	private String account;

	/ / password
	@Column(columnDefinition = VARCHAR(255) COMMENT 'login password '", nullable = false)
	private String password;

	/ / gender
	@Column(columnDefinition = "TINYINT(1) COMMENT 'gender. 0: male, 1: female '", nullable = false)
	@Enumerated
	private Gender gender;

	// Create time
	@Column(name = "created_date", columnDefinition = "Timestamp DEFAULT CURRENT_TIMESTAMP COMMENT 'create time '", nullable = false)
	private LocalDateTime createdDate;

	// Change the last time
	@Column(name = "last_modified_date", columnDefinition = "Timestamp NULL DEFAULT NULL COMMENT 'last modified timestamp '")
	private LocalDateTime lastModifiedDate;

	// Record the status
	@Column(columnDefinition = "TINYINT(1) unsigned COMMENT 'whether enabled '", nullable = false)
	private Boolean enabled;

	public Integer getId(a) {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getAccount(a) {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword(a) {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Gender getGender(a) {
		return gender;
	}

	public void setGender(Gender gender) {
		this.gender = gender;
	}

	public LocalDateTime getCreatedDate(a) {
		return createdDate;
	}

	public void setCreatedDate(LocalDateTime createdDate) {
		this.createdDate = createdDate;
	}

	public LocalDateTime getLastModifiedDate(a) {
		return lastModifiedDate;
	}

	public void setLastModifiedDate(LocalDateTime lastModifiedDate) {
		this.lastModifiedDate = lastModifiedDate;
	}

	public Boolean getEnabled(a) {
		return enabled;
	}

	public void setEnabled(Boolean enabled) {
		this.enabled = enabled;
	}

	@Override
	public String toString(a) {
		return "User [id=" + id + ", account=" + account + ", password=" + password + ", gender=" + gender
				+ ", createdDate=" + createdDate + ", lastModifiedDate=" + lastModifiedDate + ", enabled=" + enabled
				+ "]";
	}

	public static enum Gender {
		BOY, GIRL
	}
}

Copy the code

Repository

Abstract the BaseRepository

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;

@NoRepositoryBean  // The interface is not a Repository and does not need to generate a proxy implementation
public interface BaseRepository <T.ID> extends JpaRepository<T.ID>, JpaSpecificationExecutor <T>
																				// , QuerydslPredicateExecutor<T> If usedQueryDSLYou can also implement this interface{}Copy the code

Define UserRepository

import io.springboot.jpa.entity.User;

public interface UserRepository extends BaseRepository<User.Integer> {}Copy the code

Service

Abstract the BaseService

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface BaseService<T.ID> extends JpaRepository<T.ID>, JpaSpecificationExecutor <T>
														// , QuerydslPredicateExecutor<T>  
{}Copy the code

Abstract the AbstractService

import java.util.List;
import java.util.Optional;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;


import io.springboot.jpa.repository.BaseRepository;




public abstract class AbstractService<T.ID> implements BaseService <T.ID> {

	/** * generic injection */
	@Autowired
	protected BaseRepository<T, ID> baseRepository;

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public List<T> findAll(a) {
		return this.baseRepository.findAll();
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public List<T> findAll(Sort sort) {
		return this.baseRepository.findAll(sort);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public List<T> findAllById(Iterable<ID> ids) {
		return this.baseRepository.findAllById(ids);
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public <S extends T> List<S> saveAll(Iterable<S> entities) {
		return this.baseRepository.saveAll(entities);
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void flush(a) {
		this.baseRepository.flush();
	}

	@Transactional(rollbackFor = Throwable.class)
	public <S extends T> S saveAndFlush(S entity) {
		return this.baseRepository.saveAndFlush(entity);
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void deleteInBatch(Iterable<T> entities) {
		this.baseRepository.deleteInBatch(entities);
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void deleteAllInBatch(a) {
		this.baseRepository.deleteAllInBatch();
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public T getOne(ID id) {
		return this.baseRepository.getOne(id);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public <S extends T> List<S> findAll(Example<S> example) {
		return this.baseRepository.findAll(example);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public <S extends T> List<S> findAll(Example<S> example, Sort sort) {
		return this.baseRepository.findAll(example, sort);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public Page<T> findAll(Pageable pageable) {
		return this.baseRepository.findAll(pageable);
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public <S extends T> S save(S entity) {
		return this.baseRepository.save(entity);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public Optional<T> findById(ID id) {
		return this.baseRepository.findById(id);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public boolean existsById(ID id) {
		return this.baseRepository.existsById(id);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public long count(a) {
		return this.baseRepository.count();
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void deleteById(ID id) {
		this.baseRepository.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void delete(T entity) {
		this.baseRepository.delete(entity);
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void deleteAll(Iterable<? extends T> entities) {
		this.baseRepository.deleteAll(entities);
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void deleteAll(a) {
		this.baseRepository.deleteAll();
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public <S extends T> Optional<S> findOne(Example<S> example) {
		return this.baseRepository.findOne(example);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public <S extends T> Page<S> findAll(Example<S> example, Pageable pageable) {
		return this.baseRepository.findAll(example, pageable);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public <S extends T> long count(Example<S> example) {
		return this.baseRepository.count(example);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public <S extends T> boolean exists(Example<S> example) {
		return this.baseRepository.exists(example);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public Optional<T> findOne(Specification<T> spec) {
		return this.baseRepository.findOne(spec);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public List<T> findAll(Specification<T> spec) {
		return this.baseRepository.findAll(spec);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public Page<T> findAll(Specification<T> spec, Pageable pageable) {
		return this.baseRepository.findAll(spec, pageable);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public List<T> findAll(Specification<T> spec, Sort sort) {
		return this.baseRepository.findAll(spec, sort);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Throwable.class)
	public long count(Specification<T> spec) {
		return this.baseRepository.count(spec); }}Copy the code

Define the UserService

import org.springframework.stereotype.Service;

import io.springboot.jpa.entity.User;

@Service
public class UserService extends AbstractService<User.Integer> {}Copy the code

Add annotation driver

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EnableJpaRepositories(basePackages = { "io.springboot.jpa.repository" })
@EntityScan(basePackages = { "io.springboot.jpa.entity" })
public class JpaApplication {
	public static void main(String[] args) { SpringApplication.run(JpaApplication.class, args); }}Copy the code

@EnableJpaRepositories Specifies the repository package. @entityscan specifies the entity package

test

import io.springboot.jpa.JpaApplication;
import io.springboot.jpa.entity.User;
import io.springboot.jpa.service.UserService;

import java.time.LocalDateTime;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = JpaApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class JpaApplicationTest {
	
	static final Logger LOGGER = LoggerFactory.getLogger(JpaApplicationTest.class);
	
	@Autowired
	UserService userService;
	
	@Test
	public void test (a) {
		/ / store
		User user = new User();
		user.setAccount("[email protected]");
		user.setPassword("123456");
		user.setGender(User.Gender.GIRL);
		user.setEnabled(Boolean.TRUE);
		user.setCreatedDate(LocalDateTime.now());
		
		this.userService.save(user);
		
		LOGGER.info("save success.....");
		
		/ / retrieve
		User results = this.userService.findById(user.getId()).orElseGet(null);
		LOGGER.info("query result={}", results); }}Copy the code

Automatically created tables

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id'.`account` varchar(50) NOT NULL COMMENT 'Login Account'.`created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation time'.`enabled` tinyint(1) unsigned NOT NULL COMMENT 'Enabled or not'.`gender` tinyint(1) NOT NULL COMMENT 'gender. 0: male, 1: female '.`last_modified_date` timestamp NULL DEFAULT NULL COMMENT 'Last modified time'.`password` varchar(255) NOT NULL COMMENT 'Login password',
  PRIMARY KEY (`id`),
  UNIQUE KEY `UKdnq7r8jcmlft7l8l4j79l1h74` (`account`))ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='users';
Copy the code

Execution logs

Hibernate: 
    insert 
    into
        user
        (account, created_date, enabled, gender, last_modified_date, password) 
    values
        (?, ?, ?, ?, ?, ?)
2020-06-23 17:57:36.264  INFO 7612 --- [           main] i.s.jpa.test.JpaApplicationTest          : save success.....
Hibernate: 
    select
        user0_.id as id1_0_0_,
        user0_.account as account2_0_0_,
        user0_.created_date as created_3_0_0_,
        user0_.enabled as enabled4_0_0_,
        user0_.gender as gender5_0_0_,
        user0_.last_modified_date as last_mod6_0_0_,
        user0_.password as password7_0_0_ 
    from
        user user0_ 
    whereuser0_.id=? The 17:57:36 2020-06-23. 7612-303 the INFO [main] I.S.J pa. Test. JpaApplicationTest: query result=User [id=1, [email protected], password=123456, gender=GIRL, createdDate=2020-06-23T17:57:36, lastModifiedDate=null, enabled=true]
Copy the code

The last

Steps of integration

  • Add the dependent
  • Add the configuration
  • Defining entity Classes
  • Define Repositroy
  • Define the Servive
  • Add the annotation driver, specifying the Repositroy and the path to the entity class

JPA + QueryDSL is the perfect partner

Simple use of JPA, or quite many limitations, not flexible enough. But with QueryDsl, everything is different. I will write this tutorial in my spare time. Once you feel the magic of QueryDsl, you are guaranteed never to use MyBatis again (I am :eyes:)

Release springboot. IO/topic / 211 / t…