Spring Boot簡単なJunnitユニットテストと統合MyBatis改ページを実現します.


Springはbeanに依存して注入すると、MyBatisのInterceptorインターフェースのすべての種類をSql Session Factoryに注入し、pluginとして存在します.それなら、私たちはpluginを一つにまとめるのは簡単です.@Beanを使ってPageHelperオブジェクトを作成すればいいです.
1.データベースの作成
create table t_book
(
  book_id int primary key auto_increment,          -- ID
  book_name varchar(50) not null,                  --   
  book_price float not null,                       --   
  book_brief varchar(256)                          --   
);--       
2.pom.xmlにMybatisの改ページに関する依存性を追加します.

		
			com.github.pagehelper
			pagehelper
			4.1.0
		
3.エンティティクラスを作成する
package com.king.s5.model;

public class Book {
    private Integer bookId;

    private String bookName;

    private Float bookPrice;

    private String bookBrief;

    public Book(Integer bookId, String bookName, Float bookPrice, String bookBrief) {
        this.bookId = bookId;
        this.bookName = bookName;
        this.bookPrice = bookPrice;
        this.bookBrief = bookBrief;
    }

    public Book() {
        super();
    }

    public Integer getBookId() {
        return bookId;
    }

    public void setBookId(Integer bookId) {
        this.bookId = bookId;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public Float getBookPrice() {
        return bookPrice;
    }

    public void setBookPrice(Float bookPrice) {
        this.bookPrice = bookPrice;
    }

    public String getBookBrief() {
        return bookBrief;
    }

    public void setBookBrief(String bookBrief) {
        this.bookBrief = bookBrief;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bookId=" + bookId +
                ", bookName='" + bookName + '\'' +
                ", bookPrice=" + bookPrice +
                ", bookBrief='" + bookBrief + '\'' +
                '}';
    }
}
4.インターフェースと実装クラスを作成する
public interface IBookBiz {

    void addBook(Book book);

    List listBooks(Book book, PageBean pageBean);

}
package com.king.s5.biz.impl;

import com.king.s5.biz.IBookBiz;
import com.king.s5.mapper.BookMapper;
import com.king.s5.model.Book;
import com.king.s5.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookBizImpl implements IBookBiz {

    @Autowired
    private BookMapper bookMapper;

    @Override
    public void addBook(Book book) {
        bookMapper.insertSelective(book);
    }

    @Override
    public List listBooks(Book book, PageBean pageBean) {
        return bookMapper.listBooks(book);
    }
}
注意:mapperの種類とxmlは書きません.mybatisプラグイン-mybatis-generatorで自動的に生成できます.勉強が必要なものは下に残してください.
5.試験クラスの作成
1.まずbaseCaseTest(公共の基礎類)を作成し、コードの量を減らして、コードの最適化を行うことができます.
package com.king.s5;

import com.github.pagehelper.PageHelper;
import com.king.s5.biz.IBookBiz;
import com.king.s5.model.Book;
import com.king.s5.util.PageBean;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class BaseCaseTest{

    protected Book book;
    protected PageBean pageBean;

    @Before
    public void setUp() throws Exception {
        book = new Book();
        pageBean = new PageBean();
    }

    @After
    public void tearDown() throws Exception {
    }
}
2.MyBatis改ページプラグインPageHelperの実体類を登録する
package com.king.s5.util;

import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.pagehelper.PageHelper;

/**
 * mybatis   . 
 * @author Angel baby--     
 * @version v.0.1
 * @date 2018 4 8 
 */
@Configuration
public class MyBatisConfiguration {

    /**
     *   MyBatis    PageHelper 
     * @return
     */
    @Bean
    public PageHelper pageHelper() {
        System.out.println("MyBatisConfiguration.pageHelper()");
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;
    }
} 
3.改ページに必要なツール類を追加する
package com.king.s5.util;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;

public class PageBean implements Serializable {

	private static final long serialVersionUID = -7544706514503688395L;

	private int curPage = 1;//    
	private int pageRecord = 2;//    
	private int totalRecord;//     

	private boolean paginate = true;/*     ,     */

	private String url;
	private Map parameterMap;

	public PageBean() {
		super();
	}

	/**
	 *        
	 * 
	 * @param request
	 */
	public void setRequest(HttpServletRequest request) {
		this.setCurPage(request.getParameter("curPage"));
		this.setPageRecord(request.getParameter("pageRecord"));
		this.setPaginate(request.getParameter("paginate"));
		this.url = request.getContextPath() + request.getServletPath();
		this.parameterMap = request.getParameterMap();

		//   easyui   page、   rows
		String rows = request.getParameter("rows");
		String page = request.getParameter("page");
		if (null != rows && null != page) {
			this.setCurPage(request.getParameter("page"));
			this.setPageRecord(request.getParameter("rows"));
		}
	}

	public boolean isPaginate() {
		return paginate;
	}

	public void setPaginate(boolean paginate) {
		this.paginate = paginate;
	}

	public void setPaginate(String paginate) {
		paginate = null == paginate ? "" : paginate.trim();
		if ("false".equalsIgnoreCase(paginate)) {
			this.paginate = false;
		} else {
			this.paginate = true;
		}
	}

	private void setPageRecord(String pageRecord) {
		if (null != pageRecord && !"".equals(pageRecord.trim())) {
			this.pageRecord = Integer.parseInt(pageRecord);
		}
	}

	private void setCurPage(String curPage) {
		if (null != curPage && !"".equals(curPage.trim())) {
			this.curPage = Integer.parseInt(curPage);
		}
	}

	public String getUrl() {
		return url;
	}

	public void setCurPage(int curPage) {
		this.curPage = curPage;
	}

	public void setPageRecord(int pageRecord) {
		this.pageRecord = pageRecord;
	}

	public Map getParameterMap() {
		return parameterMap;
	}

	public int getTotalRecord() {
		return totalRecord;
	}

	public void setTotalRecord(int totalRecord) {
		this.totalRecord = totalRecord;
	}

	public void setTotalRecord(String totalRecord) {
		this.totalRecord = Integer.valueOf(totalRecord);
	}

	public int getCurPage() {
		return curPage;
	}

	public int getPageRecord() {
		return pageRecord;
	}

	public int getMaxPageNumber() {
		int maxPageNumber = this.totalRecord / this.pageRecord;
		maxPageNumber = totalRecord % pageRecord == 0 ? maxPageNumber : maxPageNumber + 1;
		return maxPageNumber;
	}

	public int getNextPageNumber() {
		int nextPageNumber = this.curPage + 1;
		nextPageNumber = nextPageNumber > this.getMaxPageNumber() ? this.getMaxPageNumber() : nextPageNumber;
		return nextPageNumber;
	}

	public int getPreviousPageNumber() {
		int previousPageNumber = this.curPage - 1;
		previousPageNumber = previousPageNumber < 1 ? 1 : previousPageNumber;
		return previousPageNumber;
	}

	public int getStartIndex() {
		return (this.curPage - 1) * this.pageRecord;
	}

	public int getEndIndex() {
		return this.curPage * this.pageRecord - 1;
	}

	@Override
	public String toString() {
		return "PageBean [curPage=" + curPage + ", pageRecord=" + pageRecord + ", totalRecord=" + totalRecord + "]";
	}

}
4.実現クラスの試験クラスを作成する
package com.king.s5.biz.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.king.s5.BaseCaseTest;
import com.king.s5.BaseTest;
import com.king.s5.biz.IBookBiz;
import com.king.s5.model.Book;
import com.king.s5.util.PageBean;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

public class BookBizImplTest extends BaseCaseTest {

    @Autowired
    private IBookBiz bookBiz;
//    private Book book;
//    private PageBean pageBean;
//
//    @Before
//    public void setUp() throws Exception {
//        book = new Book();
//        pageBean = new PageBean();
//    }
//
//    @After
//    public void tearDown() throws Exception {
//    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
    }

    @Test
    public void addBook() throws Exception {
    }

    @Test
    public void listBooks() throws Exception {
        PageHelper.startPage(pageBean.getCurPage(),pageBean.getPageRecord());//curPage   ,pageRecored   
        List appsList = bookBiz.listBooks(book,pageBean);
        
        //    Page   PageInfo       。           PageInfo
//        PageInfo pageInfo = new PageInfo(appsList);


//        System.out.println(appsList+"  =========== ");

        for(Book b:appsList){
            System.out.println(b);
        }
//        System.out.println(pageInfo);
    }
}
注意:もしプロジェクトの申し込みが間違っていたら、出られないのは相応の注釈を付けていないからです.もし追加しても出られないなら、それはあなたのどの部分に問題がありますか?
appication.propertiesにmybatisを配置します.
mybatis.mapper-locations=classipath*:mapper/*.xml腡ロードマップ
springAppleication類に加えて
@Spring Bootation
springAppleication類に加えて
@MapperScan(「comp.king.s 5.mapper」)//プロジェクトに対応するmapper類の経路を追加すればいいです.
springbootのいくつかの注釈
@Spring Bootation
spring bootを自動的にプログラムに必要な配置をさせるという説明は、この構成は@Configration、@EnbaleAutoConfigrationと@ComponentScanの3つの構成に相当します.
@Configration
スプリングに相当するXMLプロファイル.Javaコードを使ってタイプの安全を確認できます.
@Component
CommundLineline Runnerに協力して使用できます.プログラム起動後に基礎任務を実行します.
@Autowired
自動的にインポートします
@PathVarable
パラメータを取得します
@ビーン
@Bean表記方法はXMLに配置されたbeanに相当します.
@Value
Spring boot aplication.properties配置の属性を注入する値
@Controller
コントローラクラスを定義するために、springプロジェクトでは、ユーザからのURL要求を対応するサービスインターフェース(service層)に転送するのはコントローラが担当しています.一般的にこの注釈はクラスでは、通常の方法は注釈@Request Mappingに協力する必要があります.
@ResonseBody
例えば、jsonデータを非同期で取得し、@reponsebodyを加えると、直接にjsonデータに戻ります.
ソースが欲しいです.私のリソースライブラリにダウンロードしてください. クリックしてリンクを開きます.---------もし皆さんが私のブログが好きなら、左上の注目をクリックしてもいいです.