Build the spring cloud microservice framework: VI. database persistence layer - spring datajpa

Keywords: Programming Spring Mybatis Database MySQL

Build microservice framework (database persistence layer spring datajpa)

Used to Mybatis, this time for a change, integrate spring datajpa in SQuid.

Source address: Build microservice framework (database persistence layer spring datajpa)

Github address: SQuid

introduce

I've heard of HibernateJPA before, but I've never used it. Mybatis is always used in the project.

Spring datajpa is a set of ORM framework based on the underlying encapsulation of Hibernate. The first feeling is that the code volume is really small. Compared with the traditional Mybatis, it feels at least 60% less. Of course, most of it is embodied in xml files.

There are not many words to show in the introduction. Let's use them. 👇

use

In the squid project, we create a new squid example JPA project (since the previous example directory is deleted, we can create it according to the following hierarchical directory)

Introduce dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

Generate Java entities

If you are using IDEA, you can refer to this blog Java entity generating SpringDataJPA under IDEA To generate entity information.

Because lombok is used, there is no getter setter method rendering in the generated entity. You can learn about lombok Lombok

DAO

After generating entity information, DAO files need to be generated manually by ourselves:

public interface EdocInvoiceRepository extends JpaRepository<EdocInvoice, Long> {

}

In general, we directly inherit JPA repository, which contains all JPA processing classes and basically has all the interaction methods of the persistence layer.

JPARespository:

public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
    List<T> findAll();

    List<T> findAll(Sort var1);

    List<T> findAllById(Iterable<ID> var1);

    <S extends T> List<S> saveAll(Iterable<S> var1);

    void flush();

    <S extends T> S saveAndFlush(S var1);

    void deleteInBatch(Iterable<T> var1);

    void deleteAllInBatch();

    T getOne(ID var1);

    <S extends T> List<S> findAll(Example<S> var1);

    <S extends T> List<S> findAll(Example<S> var1, Sort var2);
}

If you have other requirements, such as the need to query according to two fields, spring datajpa fully supports:

Keyword Sample PQL snippet
And findByLastnameAndFirstname where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstname,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.age <= ?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 ... findByFirstnameNotLike
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<Age> ages) ... where x.age in ?1
NotIn findByAgeNotIn(Collection<Age> ages) ... 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)

You can also visit the official documents of spring datajpa to view: SpringDataJPA

Service & Impl & Controller

service, service.impl , controller, just write it according to the normal project. Note that if the service is to be an external interface, you can indicate @ feignclient ("squid example JPA") for reference sc-server

Post an example from the project:


public interface EdocInvoiceService {

    List<EdocInvoice> findAll();

    EdocInvoice save(EdocInvoice edocInvoice);
}

@Service
public class EdocInvoiceServiceImpl implements EdocInvoiceService {


    @Autowired
    private EdocInvoiceRepository edocInvoiceRepository;

    @Override
    public List<EdocInvoice> findAll() {
        return edocInvoiceRepository.findAll();
    }

    @Override
    public EdocInvoice save(EdocInvoice edocInvoice) {
        return edocInvoiceRepository.save(edocInvoice);
    }
}

@RestController
@RequestMapping(value = "/invoice")
public class EdocInvoiceController {

    @Autowired
    private EdocInvoiceService edocInvoiceService;

    @PostMapping(value = "/findAll")
    public List<EdocInvoice> findAll() {
        return edocInvoiceService.findAll();
    }

    @PostMapping(value = "/save")
    public EdocInvoice save(@RequestBody EdocInvoice edocInvoice) {
        return edocInvoiceService.save(edocInvoice);
    }
}

application.yaml

spring:
  application:
    name: squid-miniprogram
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://yanzhenyidai.com:3306/fapiaochi?useUnicode=true&characterEncoding=utf-8
    username: root
    password: ***
    type: com.alibaba.druid.pool.DruidDataSource
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
server:
  port: 9090

jpa.hibernate.ddl-auto :

key value
create Delete the tables in the database at startup, then create them, and do not delete the data tables at exit
create-drop Delete the table in the database at startup, then create it, and delete the data table at exit if there is no error in the table
update If the table format is inconsistent at startup, update the table and keep the original data
validate If the structure of the project startup table is not consistent, an error will be reported

The general DDL auto property uses update.

multi-table query

When complex business occurs, multi table query may be used, but JPA is not as flexible as Mybatis. It needs to create an intermediate entity to receive. My general practice is to query two tables separately and then merge them.

summary

The feeling of using spring datajpa is "fast". Compared with smaller projects, it is really recommended to use spring datajpa, which can quickly build a persistence layer, and do not care about the underlying xml files as much as Mybatis.

reference material:

SpringDataJPA-Github

SpringDataJPA-doc

Posted by vimukthi on Fri, 29 May 2020 04:31:05 -0700