MyBatis入門(三)---多個參數


一、建立表

1.1、建立表,並插入數據

 

/*
SQLyog Enterprise v12.09 (64 bit)
MySQL - 5.6.27-log : Database - mybatis
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `mybatis`;

/*Table structure for table `author` */

DROP TABLE IF EXISTS `author`;

CREATE TABLE `author` (
  `author_id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '作者ID主鍵',
  `author_username` varchar(30) NOT NULL COMMENT '作者用戶名',
  `author_password` varchar(32) NOT NULL COMMENT '作者密碼',
  `author_email` varchar(50) NOT NULL COMMENT '作者郵箱',
  `author_bio` varchar(1000) DEFAULT '這家伙很賴,什么也沒留下' COMMENT '作者簡介',
  `register_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '注冊時間',
  PRIMARY KEY (`author_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

/*Data for the table `author` */

insert  into `author`(`author_id`,`author_username`,`author_password`,`author_email`,`author_bio`,`register_time`) 
values (1,'張三','123456','123@qq.com','張三是個新手,剛開始注冊','2015-10-29 10:23:59'),(2,'李四','123asf','lisi@163.com','魂牽夢縈 ','2015-10-29 10:24:29'),(3,'王五','dfsd342','ww@sina.com','康熙王朝','2015-10-29 10:25:23'),(4,'趙六','123098sdfa','zhaoliu@qq.com','花午骨','2015-10-29 10:26:09'),(5,'錢七','zxasqw','qianqi@qq.com','這家伙很賴,什么也沒留下','2015-10-29 10:27:04'),(6,'張三豐','123456','zhangsf@qq.com','這家伙很賴,什么也沒留下','2015-10-29 11:48:00'),(7,'金庸','qwertyuiop','wuji@163.com','這家伙很賴,什么也沒留下','2015-10-29 11:48:24'),(8,'知道了','456789','456789@qq.com','哈哈哈哈哈雅虎','2015-10-29 14:03:27'),(9,'不知道','1234567890','123456@qq.com','哈哈哈哈哈雅虎','2015-10-29 14:01:16');

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

 

 

 

二、創建項目

2.1、創建項目

 

2.2、創建POJO類

 

package com.pb.mybatis.po;

import java.util.Date;

/**
 * 

* @Title: Author.java

* @Package com.pb.mybatis.po

* @ClassName Author

* @Description: TODO(Blog作者類)

* @author 劉楠 

* @date 2015-10-29 上午9:27:53

* @version V1.0
 */
public class Author {
    //作者ID
    private int authorId;
    
    //作者用戶名
    private String authorUserName;
    
    //作者密碼
    private String authorPassword;
    
    //作者郵箱
    private String authorEmail;
    
    //作者介紹
    private int authorBio;
    
    //注冊時間
    private Date registerTime;

    /**
     * @return the authorId
     */
    public int getAuthorId() {
        return authorId;
    }

    /**
     * @param authorId the authorId to set
     */
    public void setAuthorId(int authorId) {
        this.authorId = authorId;
    }

    /**
     * @return the authorUserName
     */
    public String getAuthorUserName() {
        return authorUserName;
    }

    /**
     * @param authorUserName the authorUserName to set
     */
    public void setAuthorUserName(String authorUserName) {
        this.authorUserName = authorUserName;
    }

    /**
     * @return the authorPassword
     */
    public String getAuthorPassword() {
        return authorPassword;
    }

    /**
     * @param authorPassword the authorPassword to set
     */
    public void setAuthorPassword(String authorPassword) {
        this.authorPassword = authorPassword;
    }

    /**
     * @return the authorEmail
     */
    public String getAuthorEmail() {
        return authorEmail;
    }

    /**
     * @param authorEmail the authorEmail to set
     */
    public void setAuthorEmail(String authorEmail) {
        this.authorEmail = authorEmail;
    }

    /**
     * @return the authorBio
     */
    public int getAuthorBio() {
        return authorBio;
    }

    /**
     * @param authorBio the authorBio to set
     */
    public void setAuthorBio(int authorBio) {
        this.authorBio = authorBio;
    }

    /**
     * @return the registerTime
     */
    public Date getRegisterTime() {
        return registerTime;
    }

    /**
     * @param registerTime the registerTime to set
     */
    public void setRegisterTime(Date registerTime) {
        this.registerTime = registerTime;
    }

    /** (non Javadoc)
    
     * <p>Title: toString</p>
    
     * <p>Description:重寫toString方法 </p>
    
     * @return
    
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Author [authorId=" + authorId + ", authorUserName="
                + authorUserName + ", authorPassword=" + authorPassword
                + ", authorEmail=" + authorEmail + ", authorBio=" + authorBio
                + ", registerTime=" + registerTime + "]";
    }

    
    
    
}

 

 

 

2.3、創建configruation

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
<properties resource="db.properties" />
<typeAliases>
<!--使用默認別名  -->
<package name="com.pb.mybatis.po"/>
</typeAliases>
<environments default="development">
<environment id="development">
    <transactionManager type="JDBC"/>
    <dataSource type="POOLED">
        <property name="driver" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </dataSource>
</environment>
</environments>
<mappers>
<!-- 加載映射 -->

<package name="com.pb.mybatis.mapper"/>
</mappers>
</configuration>

 

 

 

2.3、創建mapper接口

 

public interface AuthorMapper {
    
    /**
     * 
     * @Title: findById
    
     * @Description: TODO(根據查找一個用戶)
    
     * @param id
     * @return Author
     */
    public Author findAuthorById(int authorId);

}

 

 

 

2.4、創建mapper.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pb.mybatis.mapper.AuthorMapper">
<!--使用resultMap映射  type使用別名,-->
<resultMap type="Author" id="authorResultMap">
<!--主鍵  -->
<id property="authorId" column="author_id"/>
<!--普通屬性與表中的字段對應  -->
<result property="authorUserName" column="author_username"/>
<result property="authorPassword" column="author_password"/>
<result property="authorEmail" column="author_email"/>
<result property="authorBio" column="author_bio"/>
<result property="registerTime" column="register_time"/>
</resultMap>

<!--根據查找一個用戶  -->
<select id="findAuthorById" parameterType="int" resultMap="authorResultMap">
SELECT * FROM author
WHERE author_id=#{authorId}
</select>
</mapper>

 

 

 

三、傳入多個ID,進行查找使用List

3.1、更改Mapper接口

 

/**
     * 
     * @Title: findAuthors
    
     * @Description: TODO(根據多個ID進行查找)
    
     * @param idLists
     * @return List<Author>
     */
    public List<Author> findAuthors(List<Integer> idLists);

 

3.2、更改Mapper.xml

 

<!--根據多個ID查找  -->
<select id="findAuthors"  resultMap="authorResultMap">
SELECT * FROM author
WHERE author_id in
<foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>

        <!-- collection:傳入參數的名稱 index:索引: item:collection的別名 -->
</select>

 

3.3、測試

 

@Test
    public void testFindAuthors() {
        //獲取會話
        SqlSession sqlSession=sqlSessionFactory.openSession();
        //Mapper接口
        AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);
        List<Integer> list=new ArrayList<Integer>();
        
        list.add(1);
        list.add(3);
        list.add(4);
        list.add(6);
        list.add(7);
        //調用方法
        List<Author> authors=authorMapper.findAuthors(list);
        System.out.println(authors);
        //關閉會話
        sqlSession.close();
    }

 

 

四、使用Map做為參數

4.1、在Mapper接口中增加相應方法

 

/**
     * 
     * @Title: findAuthorsByMap
    
     * @Description: TODO(使用Map做為參數)
    
     * @param map
     * @return List<Author>
     */
    public List<Author> findAuthorsByMap(Map<String, Object> map);

 

4.2、更改Mapper.xml

 

<!--使用Map查找  -->
<select id="findAuthorsByMap" resultMap="authorResultMap">
SELECT * FROM author
<!--  參數使用Map的Key-->
WHERE author_username LIKE "%"#{username}"%"
or author_bio like"%"#{bio}"%"
</select>

 

4.3、測試

 

@Test
    public void testFindAuthorsByMap() {
        //獲取會話
                SqlSession sqlSession=sqlSessionFactory.openSession();
                //Mapper接口
                AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);
                Map<String, Object> map=new HashMap<String, Object>();
                map.put("username", "張");
                map.put("bio", "哈");
                
                //調用方法
                List<Author> authors=authorMapper.findAuthorsByMap(map);
                System.out.println(authors);
                //關閉會話
                sqlSession.close();
                for(Author a:authors){
                    System.out.println(a.toString());
                }
    }

 

 

 

五、直接使用多個參數

5.1、Mapper接口

 

/**
     * 
     * @Title: findAuthorsByParams
    
     * @Description: TODO(使用多個參數
    
     * @param id
     * @param username
     * @return List<Author>
     */
    public List<Author> findAuthorsByParams(int authorId,String authorUserName);

 

5.2、Mapper.xml

 

<!--直接使用多個參數  -->
<select id="findAuthorsByParams" resultMap="authorResultMap">
SELECT * FROM author
WHERE author_id=#{0}
OR author_username LIKE "%"#{1}"%"
<!-- 其中,#{0}代表接收的是dao層中的第一個參數,#{1}代表dao層中第二參數,更多參數一致往后加即可。 -->
</select>

 

5.3、測試

 

@Test
    public void testFindAuthorsByParams() {
        //獲取會話
                SqlSession sqlSession=sqlSessionFactory.openSession();
                //Mapper接口
                AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class);
                
                
                //調用方法
                List<Author> authors=authorMapper.findAuthorsByParams(6,"張");
                System.out.println(authors);
                //關閉會話
                sqlSession.close();
                for(Author a:authors){
                    System.out.println(a.toString());
                }
    }

 

 

六、直接使用多個參數注解寫法

6.1、Mapper接口

 

public List<Author> findAuthorsByParams(@Param("id") int authorId,@Param("username")String authorUserName);

 

 

 

6.2、Mapper.xml

<!--使用注解的方式使用多個參數  -->
<select id="findAuthorsByParams" resultMap="authorResultMap">
SELECT * FROM author
WHERE author_id=#{id}
or author_username LIKE "%"#{username}"%"
<!-- 使用注解的方式。,直接使用Param中的參數即可 -->
</select>

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM