天天看點

SSM-MyBatis-13:Mybatis中多條件查詢

------------吾亦無他,唯手熟爾,謙卑若愚,好學若饑-------------      

實體類

public class Book {
    private Integer bookID;
    private String bookName;
    private String bookAuthor;
    private Integer bookPrice;

    public Book() {
    }

    public Integer getBookID() {
        return this.bookID;
    }

    public void setBookID(Integer bookID) {
        this.bookID = bookID;
    }

    public String getBookName() {
        return this.bookName;
    }

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

    public String getBookAuthor() {
        return this.bookAuthor;
    }

    public void setBookAuthor(String bookAuthor) {
        this.bookAuthor = bookAuthor;
    }

    public Integer getBookPrice() {
        return this.bookPrice;
    }

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

接口中的方法

倆種形式,一種采用map,一種采用直接參數Index(索引的方式)來實作的多條件查詢

//根據多條件查詢map版
    public List<Book> findtrueBookMap(Map<String,Object> map);
    //根據多條件查詢index版
    public List<Book> findtrueBookIndex(String bookName,Integer bookPrice);      

小配置中

<!--多條件查詢map版-->
    <select id="findtrueBookMap" resultType="Book">
        select * from book WHERE bookName LIKE '%' #{bookName} '%' AND bookPrice>#{bookPrice}
    </select>
    <!--多條件查詢Index版-->
    <select id="findtrueBookIndex" resultType="Book">
        select * from book WHERE bookName LIKE '%' #{0} '%' AND bookPrice>#{1}
    </select>      

測試類中

///多條件查詢Index版
    @Test
    public void t4selectmoreIndex(){
        SqlSession session= MyBatisUtils.getSession();

        IBookDAO mapper = session.getMapper(IBookDAO.class);
        List<Book> books = mapper.findtrueBookIndex("心",40);
        for (Book items:books) {
            System.out.println(items.getBookName());
        }

        session.close();

    }

    ///多條件查詢map版
    @Test
    public void t3selectmoreMap(){
        SqlSession session= MyBatisUtils.getSession();

        IBookDAO mapper = session.getMapper(IBookDAO.class);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("bookName","心");
        map.put("bookPrice",40);
        List<Book> books = mapper.findtrueBookMap(map);
        for (Book items:books) {
            System.out.println(items.getBookName());
        }

        session.close();

    }      

這塊要解釋的真的沒有些什麼,先照貓畫虎,會用,知道每出該填什麼,入們後再去想其他,有些從字面意思就可以了解,有些則是就應該這麼寫,mybatis中獨特的寫法,就像java中的關鍵字,了解就好