MyBatis研习录(07)——MyBatis参数传递


C语言自学完备手册(33篇)

Android多分辨率适配框架

JavaWeb核心技术系列教程

HTML5前端开发实战系列教程

MySQL数据库实操教程(35篇图文版)

推翻自己和过往——自定义View系列教程(10篇)

走出思维困境,踏上精进之路——Android开发进阶精华录

讲给Android程序员看的前端系列教程(40集免费视频教程+源码)


版权声明

  • 本文原创作者:谷哥的小弟
  • 作者博客地址:http://blog.csdn.net/lfdfhl

概述

在MyBatis的使用过程中:我们通过xxxMapper.java接口向映射文件xxxMapper.xml传递参数,映射文件接收参数后再执行SQL语句。在本节教程中,我们详细介绍不同类型的参数传递。

数据准备

创建数据库mybatisDatabase和表user

DROP DATABASE IF EXISTS mybatisDatabase;
CREATE DATABASE mybatisDatabase;
use mybatisDatabase;
CREATE TABLE user(
  id INT primary key auto_increment,
  username VARCHAR(50),
  password VARCHAR(50),
  gender VARCHAR(10)
);

INSERT INTO user(username,password,gender) VALUES("lucy","123456","female");
INSERT INTO user(username,password,gender) VALUES("momo","234567","female");
INSERT INTO user(username,password,gender) VALUES("xixi","345678","female");
INSERT INTO user(username,password,gender) VALUES("pepe","456123","female");

SELECT * FROM user;

搭建开发环境

创建普通的Java工程,结构如下:
在这里插入图片描述

User

package cn.com.pojo;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class User {
	private Integer id;
	private String username;
	private String password;
	private String gender;
	public User() {
		
	}

	public User(Integer id, String username, String password, String gender) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.gender = gender;
	}

	public Integer getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", gender=" + gender + "]";
	}
	
}

mybatis-config.xml

<?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>
  <!-- 配置数据源 -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatisDatabase"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  
  <!-- 配置mapper -->
  <mappers>
    <mapper resource="cn/com/pojo/UserMapper.xml"/>
  </mappers>
  
</configuration>

log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

UserMapper.java

package cn.com.mapper;

import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import cn.com.pojo.User;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public interface UserMapper {
	
	//传递单个普通类型参数
	public User queryUserById(Integer id);
	
	//传递多个普通类型参数
	public List<User> queryUsersByUsernameAndGender(String username,String gender);
	
	//结合@Param注解传递多个普通类型参数
	public List<User> queryUsersByUsernameOrGender(@Param("username")String username,@Param("gender")String gender);
	
	//传递单个pojo作为参数
	public int insertUser(User user);
	
	//传递多个pojo作为参数
	public List<User> queryUsersByTwoUser(User firstUser,User secondUser);
	
	//传递Map类型参数
	public List<User> queryUsersByMap(Map<String, Object> paramMap);
	
	//传递List类型参数
	public List<User> queryUsersByList(@Param("userIDList")List<Integer> userIDList);
	
	//模糊查询
	public List<User> queryUsersByLike(String username);
	
}

UserMapper.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="cn.com.mapper.UserMapper">	

  <!-- 接收单个普通类型参数 -->
  <select id="queryUserById" parameterType="java.lang.Integer" resultType="cn.com.pojo.User">
    select id,username,password,gender from user where id = #{id}
  </select>
  
  <!-- 接收多个普通类型参数 -->
  <!--  
  <select id="queryUsersByUsernameAndGender" resultType="cn.com.pojo.User">
    select * from user where username = #{param1} and gender= #{param2}
  </select>
  -->
  
  <select id="queryUsersByUsernameAndGender" resultType="cn.com.pojo.User">
    select * from user where username = #{0} and gender= #{1}
  </select>
  
  <!-- 结合@Param注解接收多个普通类型参数 -->
   <select id="queryUsersByUsernameOrGender" resultType="cn.com.pojo.User">
    select * from user where username = #{username} or gender= #{gender}
  </select>

  <!-- 接收单个pojo作为参数 -->
  <insert id="insertUser" parameterType="cn.com.pojo.User">
     insert into user(username,password,gender) values (#{username},#{password},#{gender})
  </insert>

  <!-- 插入User至数据库并返回表自动生成的主键(方式一) 
  <insert id="insertUser" parameterType="cn.com.pojo.User" useGeneratedKeys="true" keyProperty="id">
     insert into user(username,password,gender) values (#{username},#{password},#{gender})
  </insert>
  -->
  
  <!-- 插入User至数据库并返回表自动生成的主键(方式二)
  <insert id="insertUser" parameterType="cn.com.pojo.User">
     <selectKey order="AFTER" keyProperty="id" resultType="int">
		select last_insert_id()
	</selectKey>
     insert into user(username,password,gender) values (#{username},#{password},#{gender})
  </insert>
   -->
  
  <!-- 接收多个pojo作为参数 -->
  <select id="queryUsersByTwoUser" resultType="cn.com.pojo.User">
    select * from user where username = #{param1.username} or gender= #{param2.gender}
  </select>
  
  <!-- 接收Map类型参数 -->
  <select id="queryUsersByMap" resultType="cn.com.pojo.User">
    select * from user where username = #{username} or gender= #{gender}
  </select>
  
  <!-- 接收List类型参数 -->
  <select id="queryUsersByList" resultType="cn.com.pojo.User">
    select * from user where id in
    <foreach item="userID" collection="userIDList" separator="," open="(" close=")">  
        #{userID}
    </foreach>
  </select>
  
  <!-- 模糊查询 -->
  <select id="queryUsersByLike" resultType="cn.com.pojo.User">
    select * from user where username like concat('%',#{username},'%')
  </select>
  
</mapper>

要点概述:

1、传递和接收单个普通类型参数

//传递单个普通类型参数
public User queryUserById(Integer id);
<!-- 接收单个普通类型参数 -->
<select id="queryUserById" parameterType="java.lang.Integer" resultType="cn.com.pojo.User">
  select id,username,password,gender from user where id = #{id}
</select>

占位符#{ }中可使用任意字符接收传递过来的参数。为提高代码的可读性,建议与原参数名保持一致。

2、传递和接收单个普通类型参数

//传递多个普通类型参数
public List<User> queryUsersByUsernameAndGender(String username,String gender);
<!-- 接收多个普通类型参数 -->
<!--  
<select id="queryUsersByUsernameAndGender" resultType="cn.com.pojo.User">
  select * from user where username = #{param1} and gender= #{param2}
</select>
-->

<select id="queryUsersByUsernameAndGender" resultType="cn.com.pojo.User">
  select * from user where username = #{0} and gender= #{1}
</select>

当传递参数有多个普通类型的参数时,在映射文件中有两种方式接收参数:

  • 使用#{0}、#{1}、…#{N}的方式依次接收参数
  • 使用#{param1}、#{param2}、…#{paramN}的方式接收参数参数(推荐方式)

3、结合@Param注解传递和接收多个普通类型参数

//结合@Param注解传递多个普通类型参数
public List<User> queryUsersByUsernameOrGender(@Param("username")String username,@Param("gender")String gender);
<!-- 结合@Param注解接收多个普通类型参数 -->
<select id="queryUsersByUsernameOrGender" resultType="cn.com.pojo.User">
   select * from user where username = #{username} or gender= #{gender}
</select>

在xxxMapper.java接口文件中可使用org.apache.ibatis.annotations.Param类型的注解@Param为参数定义别名。那么,在xxxMapper.xml映射文件中可使用别名获取参数,即#{别名}。

4、传递和接收单个pojo作为参数

//传递单个pojo作为参数
public int insertUser(User user);
<!-- 接收单个pojo作为参数 -->
<insert id="insertUser" parameterType="cn.com.pojo.User">
   insert into user(username,password,gender) values (#{username},#{password},#{gender})
</insert>

<!-- 插入User至数据库并返回表自动生成的主键(方式一) 
<insert id="insertUser" parameterType="cn.com.pojo.User" useGeneratedKeys="true" keyProperty="id">
   insert into user(username,password,gender) values (#{username},#{password},#{gender})
</insert>
-->

<!-- 插入User至数据库并返回表自动生成的主键(方式二)
<insert id="insertUser" parameterType="cn.com.pojo.User">
   <selectKey order="AFTER" keyProperty="id" resultType="int">
select last_insert_id()
</selectKey>
   insert into user(username,password,gender) values (#{username},#{password},#{gender})
</insert>
 -->

当传递的参数是单个pojo时,映射文件的占位符中可使用#{pojo的属性名}的形式获取对应参数。

5、传递和接收多个pojo作为参数

//传递多个pojo作为参数
public List<User> queryUsersByTwoUser(User firstUser,User secondUser);
<!-- 接收多个pojo作为参数 -->
<select id="queryUsersByTwoUser" resultType="cn.com.pojo.User">
  select * from user where username = #{param1.username} or gender= #{param2.gender}
</select>

当传递的参数是多个pojo时,映射文件的占位符中可使用#{paramN.pojo的属性名}的形式获取对应参数。

6、传递和接收Map类型参数

//传递Map类型参数
public List<User> queryUsersByMap(Map<String, Object> paramMap);
<!-- 接收Map类型参数 -->
<select id="queryUsersByMap" resultType="cn.com.pojo.User">
   select * from user where username = #{username} or gender= #{gender}
</select>

当传递的参数是Map时,映射文件的占位符中可使用#{Map的key}的形式获取对应参数。

7、传递和接收List类型参数

//传递List类型参数
public List<User> queryUsersByList(@Param("userIDList")List<Integer> userIDList);	
 <!-- 接收List类型参数 -->
<select id="queryUsersByList" resultType="cn.com.pojo.User">
  select * from user where id in
  <foreach item="userID" collection="userIDList" separator="," open="(" close=")">  
      #{userID}
  </foreach>
</select>

当传递的参数是List时,在xxxMapper.xml中使用foreach遍历迭代获取参数。

8、模糊查询

//模糊查询
public List<User> queryUsersByLike(String username);
<!-- 模糊查询 -->
<select id="queryUsersByLike" resultType="cn.com.pojo.User">
  select * from user where username like concat('%',#{username},'%')
</select>

在映射文件中使用数据库函数concat执行模糊查询,即concat(’%’,#{username},’%’);该方式相对安全,可避免SQL注入等危险。

MybatisTest

package cn.com.test;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import cn.com.mapper.UserMapper;
import cn.com.pojo.User;
/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class MybatisTest {

	static SqlSessionFactory sqlSessionFactory = null;

	public static SqlSessionFactory getSqlSessionFactory() {
		try {
			if (sqlSessionFactory == null) {
				InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
				SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
				sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
			}
			return sqlSessionFactory;
		} catch (Exception e) {
			
		} finally {

		}
		return null;
	}

	@Test
	public void testQueryUserById() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		User user = userMapper.queryUserById(1);
		System.out.println(user);
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testQueryUsersByUsernameAndGender() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		List<User> userList = userMapper.queryUsersByUsernameAndGender("lucy", "female");
		Iterator<User> iterator = userList.iterator();
		while (iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testQueryUsersByUsernameOrGender() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		List<User> userList = userMapper.queryUsersByUsernameOrGender("lucy", "female");
		Iterator<User> iterator = userList.iterator();
		while (iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testInsertUser() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = new User(null, "gugu", "123456", "female");
		//利用SqlSession执行数据操作
		int result = userMapper.insertUser(user);
		System.out.println("result=" + result);
		System.out.println(user);
		//提交
		sqlSession.commit();
		//关闭SqlSession
		sqlSession.close();
	}

	@Test
	public void testQueryUsersByTwoUser() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		User firstUser=new User();
		firstUser.setUsername("xixi");
		User secondUser=new User();
		secondUser.setGender("female");
		List<User> userList = userMapper.queryUsersByTwoUser(firstUser, secondUser);
		Iterator<User> iterator = userList.iterator();
		while (iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testQueryUsersByMap() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		Map<String, Object> paramMap=new HashMap<String, Object>();
		paramMap.put("username", "xixi");
		paramMap.put("gender", "female");
		List<User> userList = userMapper.queryUsersByMap(paramMap);
		Iterator<User> iterator = userList.iterator();
		while (iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testQueryUsersByList() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		List<Integer> userIDList=new ArrayList<Integer>();
		userIDList.add(1);
		userIDList.add(2);
		userIDList.add(3);
		List<User> userList = userMapper.queryUsersByList(userIDList);
		Iterator<User> iterator = userList.iterator();
		while (iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testQueryUsersByLike() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		List<User> userList = userMapper.queryUsersByLike("xi");
		Iterator<User> iterator = userList.iterator();
		while (iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
}

发布了1019 篇原创文章 · 获赞 1913 · 访问量 233万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览