Mybatis学习笔记(六)--动态sql拼接

介绍

通过mybatis提供的各种标签方法实现动态拼接sql

Mybatis动态sql---



	select * from user



Mybatis动态sql---标签

mapper接口

public List findUserBySexAndName(User user);


测试代码

@Test
public void testFindUserBySexAndName() throws Exception {
	String resource = "SqlMapConfig.xml";
	InputStream resourceAsStream = Resources.getResourceAsStream(resource);
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
	SqlSession sqlSession = sqlSessionFactory.openSession();
	UserMapper mapper = sqlSession.getMapper(UserMapper.class);
	User user = new User();
	user.setSex("0");
	user.setUsername("lin");
	List list = mapper.findUserBySexAndName(user);
	for (User user2 : list) {
		System.out.println(user2);
	}
}
	

数据库中的数据

Mybatis学习笔记(六)--动态sql拼接_第1张图片

测试效果

Mybatis动态sql---


UserVo代码

package com.janson.vo;

import java.io.Serializable;
import java.util.List;

import com.janson.pojo.User;

public class UserVo implements Serializable {
	private static final long serialVersionUID = 1L;
	private User user;
	private List list;
	private Integer[] ids;

。。。省略了get和set
}

mapper代码

public List findUserByUserVolist(UserVo vo);

测试代码

@Test
public void testfindUserByUserVolist() throws Exception {
	String resource = "SqlMapConfig.xml";
	InputStream resourceAsStream = Resources.getResourceAsStream(resource);
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
	SqlSession sqlSession = sqlSessionFactory.openSession();
	UserMapper mapper = sqlSession.getMapper(UserMapper.class);
	UserVo vo = new  UserVo();
	List l = new ArrayList<>();
	l.add("1");
	l.add("3");
	l.add("4");
	vo.setList(l);
	List list = mapper.findUserByUserVolist(vo);
	for (User user : list) {
		System.out.println(user);
	}
}

测试结果

你可能感兴趣的:(Mybatis)