Springboot與springdata JPA
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版本。
相關文章
- 【極簡版】SpringBoot+SpringData JPA 管理系統Spring Boot
- 框架系列——SpringData 、JPA 、SpringDataJPA框架Spring
- 帶你搭一個SpringBoot+SpringData JPA的環境Spring Boot
- 我選擇了MySQL和SpringData JPAMySqlSpring
- ElasticSearch與SpringBoot的整合與JPA方法的使用ElasticsearchSpring Boot
- SpringData JPA中儲存後重新整理並獲取實體Spring
- SpringBoot使用JPASpring Boot
- springboot之jpa支援Spring Boot
- SpringBoot整合系列-整合JPASpring Boot
- SpringBoot 中 JPA 的使用Spring Boot
- SpringData JDBCSpringJDBC
- SpringBoot中JPA的學習Spring Boot
- SpringBoot整合Spring Data JPASpring Boot
- SpringData操作MongoDBSpringMongoDB
- Es-SpringDataSpring
- SpringBoot資料訪問(二) SpringBoot整合JPASpring Boot
- 【SpringBoot Demo】MySQL + JPA + Hibernate + Springboot + Maven DemoSpring BootMySqlMaven
- SpringBoot JPA 表關聯查詢Spring Boot
- SpringBoot Jpa多條件查詢Spring Boot
- Spring Data JPA系列2:SpringBoot整合JPA詳細教程,快速在專案中熟練使用JPASpring Boot
- springboot(五):spring data jpa的使用Spring Boot
- springboot(十五):springboot+jpa+thymeleaf增刪改查示例Spring Boot
- SpringData 完全入門指南Spring
- Kotlin + SpringBoot + JPA 服務端開發KotlinSpring Boot服務端
- SpringBoot第九篇:整合Spring Data JPASpring Boot
- Spring Data JPA(二):SpringBoot整合H2Spring Boot
- Spring全家桶系列–SpringBoot之入門JPASpring Boot
- springboot~jpa審計欄位的自動填充Spring Boot
- SpringBoot + JPA的自學之路(三)多表連線查詢Spring Boot
- springboot 專案引入tk或者jpa 訪問報錯Spring Boot
- SpringBoot2.0應用(四):SpringBoot2.0之spring-data-jpaSpring Boot
- SpringBoot JPA查詢對映到自定義實體類Spring Boot
- 如何在SpringBoot中使用Hibernate/JPA的@NaturalId?Spring Boot
- springboot~jpa優雅的處理isDelete的預設值Spring Bootdelete
- Spring同時整合JPA與MybatisSpringMyBatis
- JPA中PersistenceUnit與PersistenceContext區別Context
- Querydsl與JPA標準的比較
- SpringBoot2.x Data JPA 多資料來源爬坑Spring Boot