spring boot學習筆記(三):數據訪問

示例代碼:https://github.com/Athlizo/spring-boot-Introductionjava

1.Spring Data JPA

用過hibernate的都知道O/R映射,將類和數據表進行映射。那JPA是什麼呢?JAP全名:Java Persistence API。只是提供了一系列規範,而Spring Data JAP提供了基於JAP的數據訪問方式極大的減小了數據庫操做的代碼量node

1.1 實例程序

使用Spring Data JPA訪問數據庫只要3步mysql

首先是引入相關jar包和配置git

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

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

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.1.1</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>
spring:
  datasource:
    url: jdbc:mysql://${url}:3306/bootintro
    username: root
    password: ${password}
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update
  jackson:
    serialization: true

其次是編寫數據庫對應的實體類github

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private Integer age;

    //省略get set
}

最後實現編寫一個藉口繼承JpaRepositoryweb

public interface PersonRepository extends JpaRepository<Person,Long>{

}

完成了..最後你就可使用PersonRepository做爲Dao層的接口操做數據庫了。看看JpaRepository中的提供接口吧redis

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

    List<T> findAll(Sort var1);

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

    <S extends T> List<S> save(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);
}

基本的CRUD操做都有了,固然若是有複雜的操做語句,也能夠定製化,就順便說起一下:spring

  1. 利用函數名,這個方法就是按照spring data jpa規定的函數模板的形式,編寫函數名達到一些特殊操做,例如findFirst10ByNameLike(String name) //查找前10條符合條件(name like)的數據
  2. 利用@Query(@Modifying)或者@NamedQuery註解
  3. 利用Specification,這個比較複雜,可是基本什麼都能作

1.2 簡要分析

JAP的自動配置類是org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,能夠看出sql

  1. JAP默認的實現者是Hibernate,而且依賴於DataSourceAutpConfiguration.
  2. 加載配置文件的類爲JpaBaseConfiguration,而且這個類中配置屬性以spring.jpa爲前綴,而且配置了JpaTransactionManager事物管理,

2. Spring REST

spring 還有一個訪問數據的方式是經過REST風格,即省略了controller和server層,直接使用url訪問dao層,我的感受這種方法有點...不過仍是比較神奇的.數據庫

2.1 實例

在上面的例子的基礎上引入

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

保留Person 和PersonRepository,配置文件同樣,完成了,

在url輸入 http://localhost:8080/persons   就會返回表爲person的全部數據

輸入 .http://localhost:8080/persons/1 查詢id爲1的數據

如何自定義

  1. 能夠在url後面加一些參數,例如分頁,再url加入參數page=1&size=2,排序加入:sort=name,desc
  2. url路徑和PersonRepository中的方法關聯(路徑爲 http://localhost:8080/persons/search/${ref-path}
  3. 保存:發送post請求,把要保存的內容放在請求體
  4. 更新:PUT請求,url爲查詢的url(例如http://localhost:8080/persons/1),而且把更新的放在請求體,
  5. 刪除:送delete請求(例如http://localhost:8080/persons/1),
  6. 定製根路徑,經過在配置文件中加入 spring.data.rest.base-path= /api  那麼全部rest接口都要在前面加上路徑/api  例如 http://localhost:8080/api/person/1

3. 緩存

spring 中使用 cacheManager來控制緩存.主要包括:

  1. 使用內存:SimplerCacheManager(使用簡單的Collection來存儲,主要測試用),ConcurrentMapCacheManager使用ConcurrentMap存儲
  2. 使用第三方緩存,例如Redis,Guava等,主要經過加入相關jar包和配置便可替換

配置

3.1 實例

1. 使用註解的方式操做緩存

支持緩存只須要在配置類中加入@EnableCaching,默認是使用SimplerCacheManager,而後,經過3個註解操做緩存,貼一下代碼立刻就明白

@Service
public class DemoServiceImp implements DemoService {
    @Autowired
    PersonRepository personRepository;

    @Override
    @CacheEvict(value = "person")
    public void delete(Long id) {
        personRepository.delete(id);
    }

    @Override
    @Cacheable(value = "person")
    public Object findById(Long id) {
        return personRepository.findOne(Example.of(person));
    }

    @Override
    @CachePut(value = "person", key = "#person.id")
    public Object save(Person person) {
        return personRepository.save(person);
    }
}

就是@CacheEvict-刪除緩存,@Cacheable-查找,@CachePut-加入緩存 (上面這個邏輯和mybatis開啓二級緩存相似)

2.使用CacheManager(我的推薦這種方式,更靈活)

配置redis

redis的相關配置包括

spring.redis.database= # database name  
spring.redis.host=localhost # server host  
spring.redis.password= # server password  
spring.redis.port=6379 # connection port  
spring.redis.pool.max-idle=8 # pool settings ...  
spring.redis.pool.min-idle=0  
spring.redis.pool.max-active=8  
spring.redis.pool.max-wait=-1  
spring.redis.sentinel.master= # name of Redis server  
spring.redis.sentinel.nodes= # comma-separated list of host:port pairs

若是你要默認的CacheManager使用redis還須要增長

spring.cache.type=redis

這樣代碼裏面注入的CacheManager 就使用的是redis

示例代碼:https://github.com/Athlizo/spring-boot-Introduction

相關文章
相關標籤/搜索