使用 java 对象传递参数, java 对象的属性值就是 sql 需要的参数值。 每一个属性就是一个参数。
语法格式: #{ property,javaType=java 中数据类型名,jdbcType=数据类型名称 }
javaType, jdbcType 的类型 MyBatis 可以检测出来,一般不需要设置。常用格式 #{ property }
mybatis-3.5.1.pdf 第 43 页 4.1.5.4 小节:
接口方法:
public abstract List<Student> selectStudents2(Student student);
或
<select id="selectStudents2" resultType="com.wzy.pojo.Student">
select id,name,gender,age,birthday,files from student where id = #{id} or name =#{name}
</select>
测试方法:
package com.wzy.dao;
import com.wzy.pojo.Student;
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 java.io.IOException;
import java.io.InputStream;
import static org.junit.Assert.*;
public class StudentDaoTest3 {
@Test
public void selectWhere() {
SqlSession sqlSession = null;
try {
//1.mybatis 主配置文件
String config = "MyBatis.xml";
//2.读取主配置文件
InputStream resourceAsStream = Resources.getResourceAsStream(config);
//3.创建 SqlSessionFactory 对象,用于获取 sqlSession sql语句持久化对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//4.获取 sqlSession 语句持久化对象
sqlSession = sqlSessionFactory.openSession();
//5.Dao代理,获取接口对象
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
//6.出入参数,调用查询方法.查询数据
Student student = studentDao.selectWhere(1, "李四");
//7.输出结果
System.out.println(student.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
//8.释放资源
if (sqlSession != null) {
sqlSession.close();
}
}
}
}
