Home Java javaTutorial Getting Started with MyBatis (3) --- Multiple Parameters

Getting Started with MyBatis (3) --- Multiple Parameters

Dec 21, 2016 pm 02:27 PM

一、建立表

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、创建项目

Getting Started with MyBatis (3) --- Multiple Parameters

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 class)

* @author Liu Nan

* @date 2015-10-29 9:27:53 AM

* @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)
   
    *

Title: toString


   
    *

Description:重写toString方法


   
    * @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

 


br/>  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">









   
   
       
       
       
       
   









 

 

 

2.3、创建mapper接口

 

public interface AuthorMapper {    
   /**
*
* @Title: findById

* @Description: TODO (find a user based on it)

* @param id
* @return Author*/
   public Author findAuthorById(int authorId);

}

 

 

 

2.4、创建mapper.xml

 

br/>  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

 

 

 

三、传入多个ID,进行查找使用List

3.1、更改Mapper接口

 

/**
*
* @Title: findAuthors

* @Description: TODO (Search based on multiple IDs)

* @param idLists
* @return List*/
   public List findAuthors(List idLists);

 

3.2、更改Mapper.xml

 


 

3.3、测试

 

@Test public void testFindAuthors() {         //Get the session
                sqlsession sqlSession=sqlSessionFactory.openSession();             //Mapper interface
            AuthorMapper=sqlSession.getMapper(A uthorMapper.class);
List list=new ArrayList();
       
          list.add(1);
          list.add(3); //Call method
List authors=authorMapper.findAuthors(list);
System.out.println(authors); //Close session sqlSession.close();
}



4. Use Map as parameter

4.1. Add corresponding methods to the Mapper interface

/**

*

* @Title: findAuthorsByMap


* @Description: TODO (use Map as parameter)

* @param map
* @return List*/
public List findAuthorsByMap(Map map);



4.2. Change Mapper. xml



4.3、Test

@Test public void testFindAuthorsByMap() {                                                                                                                                                                                                  sqlSession and‑‑       sqlSession=sqlSessionFactory.openSession();‑‑               pper(AuthorMapper.class);

Map map=new HashMap() ;

                   map.put("username", "张"); 

                  map.put(("bio", " "); List authors=authorMapper.findAuthorsByMap(map);
System .out.println(authors);                                 sqlSession.close(); ));
                                                            


5. Use multiple parameters directly

5.1, Mapper interface



/**
* *

* @Title: findAuthorsByParams

* @Description: TODO(Use multiple parameters

* @param id

* @param username

* @return List*/

public List findAuthorsByParams(int authorId,String authorUserName);

5 .2. Mapper.xml







5.3, test

@Test public void testFindAuthorsByParams() { //Get session
           SqlSession sqlSession=sqlSessionFactory.openSession();                                                AuthorMapper authorMapper=sqlSession.getMapper(AuthorMapper.class); > ; authors=authorMapper.findAuthorsByParams(6,"张");
System.out.println(authors); :authors){
                System.out.println(a .toString());
                                                                                                                             findAuthorsByParams(@Param("id") int authorId,@Param("username")String authorUserName);





6.2, Mapper.xml

The above is the content of MyBatis Getting Started (3)---multiple parameters. For more related content, please pay attention to the PHP Chinese website (www.php .cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

iBatis vs. MyBatis: Which one is better for you? iBatis vs. MyBatis: Which one is better for you? Feb 19, 2024 pm 04:38 PM

iBatis vs. MyBatis: Which should you choose? Introduction: With the rapid development of the Java language, many persistence frameworks have emerged. iBatis and MyBatis are two popular persistence frameworks, both of which provide a simple and efficient data access solution. This article will introduce the features and advantages of iBatis and MyBatis, and give some specific code examples to help you choose the appropriate framework. Introduction to iBatis: iBatis is an open source persistence framework

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

Various ways to implement batch deletion operations in MyBatis Various ways to implement batch deletion operations in MyBatis Feb 19, 2024 pm 07:31 PM

Several ways to implement batch deletion statements in MyBatis require specific code examples. In recent years, due to the increasing amount of data, batch operations have become an important part of database operations. In actual development, we often need to delete records in the database in batches. This article will focus on several ways to implement batch delete statements in MyBatis and provide corresponding code examples. Use the foreach tag to implement batch deletion. MyBatis provides the foreach tag, which can easily traverse a set.

Comparative analysis of the functions and performance of JPA and MyBatis Comparative analysis of the functions and performance of JPA and MyBatis Feb 19, 2024 pm 05:43 PM

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

Detailed explanation of how to use MyBatis batch delete statements Detailed explanation of how to use MyBatis batch delete statements Feb 20, 2024 am 08:31 AM

Detailed explanation of how to use MyBatis batch delete statements requires specific code examples. Introduction: MyBatis is an excellent persistence layer framework that provides rich SQL operation functions. In actual project development, we often encounter situations where data needs to be deleted in batches. This article will introduce in detail how to use MyBatis batch delete statements, and attach specific code examples. Usage scenario: When deleting a large amount of data in the database, it is inefficient to execute the delete statements one by one. At this point, you can use the batch deletion function of MyBatis

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Feb 23, 2024 pm 08:13 PM

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? During the development process, efficient data access has always been one of the focuses of programmers. For persistence layer frameworks like MyBatis, caching is one of the key methods to improve data access efficiency. MyBatis provides two caching mechanisms: first-level cache and second-level cache. The first-level cache is enabled by default. This article will introduce the mechanism of MyBatis first-level cache in detail and provide specific code examples to help readers better understand

Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Feb 25, 2024 pm 12:30 PM

Analysis of MyBatis' caching mechanism: The difference and application of first-level cache and second-level cache In the MyBatis framework, caching is a very important feature that can effectively improve the performance of database operations. Among them, first-level cache and second-level cache are two commonly used caching mechanisms in MyBatis. This article will analyze the differences and applications of first-level cache and second-level cache in detail, and provide specific code examples to illustrate. 1. Level 1 Cache Level 1 cache is also called local cache. It is enabled by default and cannot be turned off. The first level cache is SqlSes

MyBatis Generator configuration parameter interpretation and best practices MyBatis Generator configuration parameter interpretation and best practices Feb 23, 2024 am 09:51 AM

MyBatisGenerator is a code generation tool officially provided by MyBatis, which can help developers quickly generate JavaBeans, Mapper interfaces and XML mapping files that conform to the database table structure. In the process of using MyBatisGenerator for code generation, the setting of configuration parameters is crucial. This article will start from the perspective of configuration parameters and deeply explore the functions of MyBatisGenerator.

See all articles