栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

mybatis传参

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 selectMulitParm(@Param("p_name") String name,@Param("p_age") Integer age);
     //p_name,p_age 是自定义
}

2.在mybatis的sql 映射文件中接受参数





    
        select * from student where name=#{p_name} or age=#{p_age}
     


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

}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/305884.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号