Springboot與springdata JPA

weixin_34054866發表於2017-11-01

springboot的版本為1.4.3.RELEASE

基本的配置

yaml配置檔案:

spring:
  datasource:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: root

倉庫的程式碼:

public interface HospitalResponsity extends JpaRepository<Hospital, Integer> {
}

其中,Hospital是類名,Integer是主鍵型別。
然後注入到service中就可以使用了。

基本的語法

對於其方法名的定義,遵循駝峰命令,有一些基本的語法。
如find是查詢、save是儲存、delete是刪除、insert是新增。
And是和、Or是或者、Containing是包含,相當於前後%的like。

雙資料來源

因專案需要讀寫分離,所以採用雙資料來源進行處理。
yaml檔案配置:

spring:
#資料來源的配置#
  datasource:
  #主讀副寫
      primary:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf-8&useSSL=false
        username: root
        password: root
      secondary:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf-8&useSSL=false
        username: root
        password: root
# 如果需要h2資料庫的
#        url:  jdbc:h2:D:/tools/H2/test
#        username: sa
#        password: sa

Java的config檔案配置(boot版本1.4.3):
總配置源DataSourceConfig.java檔案:


import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * Created by lingbao on 2017/10/30.
 *
 * @author lingbao
 * @Description
 * @Modify
 */
@Configuration
public class DataSourceConfig {

    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix="spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @Primary
    @ConfigurationProperties(prefix="spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

}

主資料來源PrimaryConfig.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryPrimary",
        transactionManagerRef="transactionManagerPrimary",
        basePackages= {"com.kindo.vine.*.repository.read"}) //設定該資料來源要監控的Repository所在位置
public class PrimaryConfig {

    @Autowired @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;

    @Primary
    @Bean(name = "entityManagerPrimary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactoryPrimary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(primaryDataSource)
                .properties(getVendorProperties(primaryDataSource))
                .packages("com.kindo.vine.*.entity") //設定實體類所在位置
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }

    @Autowired
    private JpaProperties jpaProperties;

    private Map<String, String> getVendorProperties(DataSource dataSource) {
        return jpaProperties.getHibernateProperties(dataSource);
    }

    @Primary
    @Bean(name = "transactionManagerPrimary")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }

}

Java的config檔案配置(boot版本2.0.0.BUILD-SNAPSHOT):


import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * Created by lingbao on 2017/11/28.
 *
 * @author lingbao
 * @Description
 * @Modify
 */
@Configuration
public class DataSourceConfig {
    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.primary")
    public DataSourceProperties primaryDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.primary")
    public DataSource primaryDataSource() {
        return primaryDataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.secondary")
    public DataSourceProperties secondaryDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return secondaryDataSourceProperties().initializeDataSourceBuilder().build();
    }
}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryPrimary",
        transactionManagerRef="transactionManagerPrimary",
        basePackages= {"com.kindo.lily.business.*.repository.write"}) //設定Repository所在位置
public class PrimaryConfig {

    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;

    @Primary
    @Bean(name = "entityManagerPrimary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactoryPrimary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(primaryDataSource)
                .packages("com.kindo.lily.business.*.entity") //設定實體類所在位置
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }

    @Primary
    @Bean(name = "transactionManagerPrimary")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }

}

從資料來源同理,primary變成secondary就OK,去掉@Primary即可。此處略過。

在Service層需要注入兩個資料來源,然後根據需要使用指定的資料來源。


DSL的使用:
使用QueryDslPredicateExecutor介面來實現:

public interface UserRespository extends JpaRepository<User,Long>, JpaSpecificationExecutor {
//根據JPA的語法寫出的查詢
    List<Dict> findAllByName(String name);

//以下兩種方法等效
@Query(nativeQuery = true,value = "SELECT * FROM test_dict t1 WHERE " +
            "t1.id IN ( SELECT pid FROM test_dict t WHERE t.name LIKE concat('%',?1,'%'))" +
            "OR t1.id IN (SELECT id FROM test_dict t WHERE t.name LIKE concat('%',?1,'%'))")
    List<Dict> findAllByName1(String name);

    @Query("SELECT t1 FROM Dict t1 WHERE " +
            "t1.id IN ( SELECT pid FROM Dict t WHERE t.name like CONCAT('%',:name,'%'))" +
            "OR t1.id IN (SELECT id FROM Dict t WHERE t.name LIKE CONCAT('%',:name,'%'))")
    List<Dict> findAllByName2(@Param("name") String name);
}

Tips:JPA上寫SQL的like的值,要用concat來拼接的,不能直接用單引號或者雙引號等。

單實體模糊查詢:

//下面的實現功能為模糊查詢userName,確定查詢age,定值條件state,最後id倒序查詢分頁。

public Page<User> queryAll(String userName, String age, Pageable pageable) throws CommonException {

        Specification querySpecifi = (root, query, cb) -> {
            Predicate predicate = cb.equal(root.get("state"), "0");
            if (null != name) {
                //root.get("userName")表示式,userName為實體中的欄位名稱。
                //如果使用者名稱傳空字串的話,%+""+%表示查詢全部。
                //如果使用者名稱傳帶空格的空字串的話,%+" "+%表示使用者的意願是查詢帶"空格"的全部。
                predicate = cb.and(cb.like(root.get("userName"), "%" + name + "%"));
            }

            if (StringUtils.isNotBlank(age)) {
                predicate = cb.and(cb.equal(root.get("age"), age));
            }
            query.orderBy(cb.desc(root.get("id").as(Integer.class)));
            return predicate;
        };
        //返回SpringJPA裡的page型別
        Page page = medicineReadRepository.findAll(querySpecifi, pageable);

        return page;
    }

注意,在多表關聯的實體中,必須引入相關的實體類(以集合或實體類物件的方式),並標註@OneToMany等註解。

原始碼:https://github.com/lingbao08/springboot-example.git
注意原始碼為後來補充,boot版本為2.0.1版本。

相關文章