Spring Boot+Spring Data JPA+Spring Cache

13580 ワード

この文書ではspring bootを使用してプロジェクトプロジェクトを迅速に構築し、spring data jpa制御データアクセスサービス層、spring cacheキャッシュクエリーデータ
1.pom.xml構成情報およびアプリケーション.properties
<strong><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.springframework</groupId>
	<artifactId>com-my-data-cache</artifactId>
	<version>0.1.0</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.1.RELEASE</version>
	</parent>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
	
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<!-- data jpa   -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
			<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>
		<dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-thymeleaf</artifactId>  
        </dependency>  
		<!--      -->
			<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jetty</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
		</dependency>
		<!--   cache -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>
		<!-- redis   -->
	<!-- 	<dependency>  
          <groupId>org.springframework.boot</groupId>  
          <artifactId>spring-boot-starter-redis</artifactId>  
      </dependency>   -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-commons</artifactId>
		</dependency>
		<!--     log -->
			<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j</artifactId>
		</dependency>
		<!--        -->
		<!-- <dependency>
		 <groupId>org.springframework.boot</groupId>
		  <artifactId>spring-boot-starter-security</artifactId> 
			</dependency>  -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
			<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
			<dependency>
				<groupId>org.hibernate</groupId>
				<artifactId>hibernate-entitymanager</artifactId>
			</dependency>
			<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
</strong>
# primary datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost/mydat
spring.datasource.username=root
spring.datasource.password= wb12345

2.新規エンティティークラスオブジェクトBOOK
<strong>package com.my.data.cache.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="book")
public class Book implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6283522837937163003L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = true)
	private Integer id;
    private String isbn;
    private String title;

    public Book(String isbn, String title) {
        this.isbn = isbn;
        this.title = title;
    }
    public Book() {
	}
	public Book(int id, String isbn, String title) {
		super();
		this.id = id;
		this.isbn = isbn;
		this.title = title;
	}


	public int getId() {
		return id;
	}




	public void setId(int id) {
		this.id = id;
	}




	public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return "Book{" + "isbn='" + isbn + '\'' + ", title='" + title + '\'' + '}';
    }
}
</strong>

3.Spring Data JPA持久層技術を採用したDAOインタフェースを作成し、ネーミングクエリー、注釈クエリー、ネーミングパラメータクエリーなどのクエリー方式を採用することができる.
<strong>package com.my.data.cache.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import com.my.data.cache.domain.Book;
/**
 *   
 * @author wbw
 *
 */
public interface BookRepository extends JpaRepository<Book, Integer> {

  @Query("select b from Book b  where 1=1")
  public   List<Book> findBookAll();
  /**
   *   isbn  
   * @param name
   * @return
   */
  @Query("select  b from Book b where b.id =?1")
  public  Book findById(Integer bid);
   /**
    *   size  
    * @return
    */
  @Query("select count(*) from Book where 1=1 ")
  public int countBook();
  /**
   *          findBy+  
   * @param isbn
   * @return
   */
  public Book findByIsbn(String isbn);

}
</strong>

4.サービス業務ロジック処理層インタフェース及び実現インタフェースの作成
<strong>package com.my.data.cache.service;

import java.util.List;

import com.my.data.cache.domain.Book;

public interface BookService {

	public Book findById(Integer bid);

	public List<Book> findBookAll();

	public void insertBook(Book book);

	public Book findByTitle(String title);
	
	public int countBook();
	
	public void modifyBook(Book book);
	
	 public Book findByIsbn(String isbn);
	
	
}
</strong>
<strong>package com.my.data.cache.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.my.data.cache.annotation.LogAnnotation;
import com.my.data.cache.domain.Book;
import com.my.data.cache.exception.MyException;
import com.my.data.cache.repository.BookRepository;
import com.my.data.cache.service.BookService;

@Service
@Transactional
public class BookServiceImpl  implements BookService{
	private static final Logger log = LoggerFactory.getLogger(BookServiceImpl.class);
	@Autowired
	private BookRepository bookRepository;
	
	/*@PersistenceContext
	private EntityManager em;*/
	
	//      andCache,       bid       (        )     key
	@Cacheable(value="andCache",key="#bid+'findById'")
	//@LogAnnotation(value="  Id  Book")
	public Book findById(Integer bid) {
		this.simulateSlowService();
		return bookRepository.findById(bid);
	}
	
	@Override
	public List<Book> findBookAll() {
		return bookRepository.findBookAll();
	}
    
	//      andCache,    title     32       ,               key 
	@Cacheable(value="andCache",condition="#title.length >5") 
	public Book findByTitle(String title){
		return null;
		
	}
	/**
	 *   
	 * @param book
	 * @return
	 */
	public void insertBook(Book book){
		bookRepository.save(book);
	}
	
	@Override
	public int countBook() {
		return bookRepository.countBook();
	}  
	//     key    
	@CacheEvict(value="andCache",key="#book.id + 'findById'")
	public void modifyBook(Book book) {
		log.info("      "+book.getId()+"findById");
		bookRepository.save(book);
	}
	
	//         
	@CacheEvict(value="andCache",allEntries=true,beforeInvocation=true)  
	public void ReservedBook() {  
		log.info("       ");  
	}

	// Don't do this at home
    private void simulateSlowService() {
        try {
            long time = 5000L;
            Thread.sleep(time);
        } catch (InterruptedException e) {
            throw new MyException("    ", e);
        }
    }

	@Override
	public Book findByIsbn(String isbn) {
		return bookRepository.findByIsbn(isbn);
	}
}
</strong>

5.コントロールコントローラの作成
<strong>package com.my.data.cache.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.my.data.cache.domain.Book;
import com.my.data.cache.service.BookService;

@RestController 
@RequestMapping("/user")  
public class BookController {
	private static final Logger log = LoggerFactory.getLogger(BookController.class);
    
	@Autowired
    private BookService bookService;
	
    
    @RequestMapping("/{id}")
	public @ResponseBody Book index(@PathVariable("id") Integer id){
		Book b = bookService.findById(id);
	    log.info(b.getIsbn()+"------>"+b.getTitle());
  		return b;
	}
    
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public  @ResponseBody List<Book> list(){
    	List<Book> b = bookService.findBookAll();
		return  b;
    	
    }
    @RequestMapping(value = "/add")
    public String  insertBook(){
    	Book b = new Book();
    	b.setId(4);
    	b.setIsbn("1111");
    	b.setTitle("    ");
    	bookService.insertBook(b);
    	return "success";
    	
    }    
    /**
     *   
     * @return
     */
    @RequestMapping(value = "/update")
    public String update(){
    	Book b = new Book();
    	b.setId(1);
    	b.setIsbn("1");
    	b.setTitle("    ");
    	bookService.modifyBook(b);
    	return "success";
    }
}
</strong>

6.テスト
<strong>package com.my.data.cache;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

import com.my.data.cache.domain.Book;
import com.my.data.cache.service.BookService;


/**
 * 
 *    
 *
 */
@SpringBootApplication
@EnableCaching//  cahce  
public class Application1  implements CommandLineRunner{
	
	@Autowired
    private BookService bookService;
	@Override
	public void run(String... args) throws Exception {
		Book b1 = bookService.findByIsbn("1");
		Book b2 = bookService.findByIsbn("2");
		Book b3 = bookService.findById(3);
	    System.out.println(b1);
        System.out.println(b2);
        System.out.println(b3);
		
	}
	public static void main(String[] args) {
		 SpringApplication.run(Application1.class,args);
	}

}</strong>

Spring Cache
3.1からSpringはCacheのサポートを導入した.その使用方法と原理はSpringのトランザクション管理のサポートに似ています.Spring Cacheはメソッドに作用し,その核心思想は,キャッシュメソッドを呼び出すとメソッドパラメータと戻り結果をキー値ペアとしてキャッシュに格納し,次回同じパラメータを用いてメソッドを呼び出すとそのメソッドを実行せず,キャッシュから直接結果を取得して返すことである.Spring Cacheを使用するときは、同じメソッドパラメータに対して同じキャッシュメソッドが返されることを保証します.
 Spring Cacheを使用するには、2つの側面が必要です.
n  キャッシュの使用方法を宣言
n  SpringによるCacheのサポートの構成
Springのトランザクション管理のサポートと同様に、SpringのCacheのサポートには、注釈ベースとXMLベースの構成の2つの方法で詳細に関する情報リンクがあります.
https://www.ibm.com/developerworks/cn/opensource/os-cn-spring-cache/