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

相关文章
相关标签/搜索