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 selectMulitParm(@Param("p_name") String name,@Param("p_age") Integer age);
//p_name,p_age 是自定义
}
2.在mybatis的sql 映射文件中接受参数
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 = dao.selectMulitParm("xxx",20);
for(Student stu:student){
System.out.println(stu);
}
sqlSession.close();
}
}



