Build spring cloud microservice framework: VI. database persistence layer – springdatajpa

Time:2020-9-22

Build microservice framework (database persistence layer spring datajpa)

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

I’m used to mybatis. This time, I want to change my taste and integrate spring datajpa in squid.

Source address of this article: build microservice framework (database persistence layer spring datajpa)

GitHub address: Squid


introduce

I’ve heard about it beforeHibernateJPA, which has never been used, but has been used in the projectMybatis

Springdatajpa is a set of ORM framework based on Hibernate’s underlying encapsulation. The first feeling of using it is that the amount of code is really small. Compared with the traditional mybatis, it is at least 60% less. Of course, most of them are reflected in XML files.

There are not too many words to show. Let’s use them.


use

In squid project, we create a new onesquid-example-jpa(since the previous example directory has been deleted, you can create a new one according to the following hierarchical directory)

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

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>

Generating Java entities

If you are using idea, you can refer to the Java entity of spring datajpa generated under idea in this blog
To generate entity information.

Because Lombok is used, it is not in the generated entitygetter setterMethod rendering. You can learn about Lombok

DAO

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

public interface EdocInvoiceRepository extends JpaRepository<EdocInvoice, Long> {

}

In general, what we inherit directly isJpaRepositoryThis is a class that contains all JPA processing 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 query based on 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 documentation of springdatajpa: springdatajpa

Service & Impl & Controller

service、 service.impl , controller, just write it according to the routine project. Note that if the service is to be used as an external interface, it can be specified@FeignClient("squid-example-jpa")You can refer to SC server

Post examples from projects:


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 when exiting
create-drop Delete the table in the database at startup, then create it, and delete the data table when exiting. If there is no error in the table
update If the table format is inconsistent at startup, the table will be updated and the original data will be retained
validate Check the project startup table structure. If it is inconsistent, an error will be reported

Generalddl-autoAttribute usageupdateThat’s fine.

multi-table query

When complex business occurs, multi table query may be used. However, 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 data JPA is one word“fast”Compared with smaller projects, it is really recommended to use spring datajpa, which can quickly build a persistence layer, and doesn’t have to care about the underlying XML files as much as mybatis.

reference material:

SpringDataJPA-Github

SpringDataJPA-doc