mybatis传参

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();
    }

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值