java 类中传递参数给mybatis 能够是数据交互更灵活。结合之前的项目文件mybatis入门和动态代理。参数传递过程这样写。
1.在接口类中写入要传递的参数
例如我们按照id查询一个学生的信息,那么在接口文件类com.ajuncode.Dao.StudentDao中这样传递一个形式参数,我们的代码如下:
package com.ajuncode.Dao;
import com.ajuncode.domain.Student;
import java.util.List;
public interface StudentDao {
// 根据主键来查询某个学生(单个参数)
public Student selectStudentById(Integer id);
// 根据名字和年龄来查询学生信息(多个参数使用@Param命名参数)
public List<Student> selectMulitParm(@Param("p_name") String name,@Param("p_age") Integer age);
//p_name,p_age 是自定义
}
2.在mybatis的sql 映射文件中接受参数
<?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.ajuncode.Dao.StudentDao">
<!--
parameterType :dao接口方法中参数的类型
paramterType 它的值是java的数据类型全限定名称或者是mybatis定义的别名
例如:parameterType = "java.lang.Integer"
parameterType="int"
但是该参数并非强制的需要的,mybatis通过反射机制能够发现接口参数的数据类型
-->
<select id="selectStudentById" parameterType="int" resultType="com.ajuncode.domain.Student">
select id,name,email,age from student where id=#{id}
</select>
<select id="selectMulitParm" resultType="com.ajuncode.domain.Student">
select * from student where name=#{p_name} or age=#{p_age}
</select>
</mapper>
3.测试代码
在我的项目中测试类命名为com.ajuncode.Testmybatis2
package com.ajuncode;
import com.ajuncode.Dao.StudentDao;
import com.ajuncode.domain.Student;
import com.ajuncode.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class Testmybatis2 {
@Test
public void testSelectStudentById(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
Student student = dao.selectStudentById(1002);
System.out.println(student);
}
@Test
public void testSelectMultiParam(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
List<Student> student = dao.selectMulitParm("xxx",20);
for(Student stu:student){
System.out.println(stu);
}
sqlSession.close();
}
}
4754

被折叠的 条评论
为什么被折叠?



