mybatis中怎么通过外键查询_Mybatis【8】 Mybatis返回List或者Map以及模糊查询怎么搞?...

本文介绍了在Mybatis中如何通过外键查询,包括返回List查询所有学生、返回Map以学生名字为key、以及如何进行模糊查询。详细讲解了接口定义、SqlSession的方法使用,特别强调了模糊查询时防止SQL注入的注意事项。
摘要由CSDN通过智能技术生成

代码直接放在Github仓库【https://github.com/Damaer/Mybatis-Learning 】,可直接运行,就不占篇幅了。

  • 1.返回List(查询所有学生)

  • 2.返回Map(查询所有学生,key是名字,value是学生对象)

  • 3.模糊查询

定义获取 sqlSession实例的工具类如下:
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 java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    static private SqlSessionFactory sqlSessionFactory;

    static public SqlSession getSqlSession() {
        InputStream is;
        try {
            is = Resources.getResourceAsStream("mybatis.xml");
            if (sqlSessionFactory == null) {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            }
            return sqlSessionFactory.openSession();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

1.返回List(查询所有学生)

定义接口:

// 返回所有学生的信息List
public List selectAllStudents();

使用SqlSession.selectList()这个方法对sql进行调用:

public List selectAllStudents() {
        List students ;try {
            sqlSession = MyBatisUtils.getSqlSession();
            students = sqlSession.selectList("selectAllStudents");//查询不用修改,所以不用提交事务
        } finally {if (sqlSession != null) {
                sqlSession.close();
            }
        }return students;
    }

sql语句如下,返回类型是Student,这里写的是别名,这是因为定义过别名,否则需要写全路径名:

    
    
    "selectAllStudents" resultType="Student">
        select id,name,age,score from student

2.返回Map(查询所有学生,key是名字,value是学生对象)

定义接口:

// 返回所有学生的信息Map
public Map selectAllStudentsMap();

接口实现类,使用selectMap(),里面有两个参数,一个是sql的id,一个是需要当成key的字段,注意,如果这个key在数据表里面有重复的,那么后面查出来的value会覆盖掉前面的value:

public Map selectAllStudentsMap() {
        Map map=new HashMap();
        /**
         * 可以写成Map map=new HashMap();
         */
        try {
            sqlSession=MyBatisUtils.getSqlSession();
            map=sqlSession.selectMap("selectAllStudents", "name");
            //查询不用修改,所以不用提交事务
        } finally{if(sqlSession!=null){
                sqlSession.close();
            }
        }return map;
    }

sql语句:用的同样是返回List的sql语句,其实这个map的处理是map=sqlSession.selectMap("selectAllStudents", "name");这句话帮我们处理的。

    
    
    <select id="selectAllStudents" resultType="Student">
        select id,name,age,score from student
        
    select>

3.模糊查询

我们需要查询名字的时候一般是模糊查询。那么使用下面的sql即可:

    
    
    
    
    
    <select id="selectStudentsByName" resultType="Student">
        
        
        select id,name,age,score from student where name like '%${value}%'
    select>

值得注意的是关于占位符的问题,如果只是一个int类型传进来,如果使用#,我们不需要和传入的名字一样,比如#{}里面写xxx都可以:


    "deleteStudentById" >
        delete from student where id=#{xxx}

当传入的是对象,那么我们就不能随便写了,因为随便写就不知道用哪一个属性了。

"updateStudent">
 update student set name=#{name},age=#{age},score=#{score} where id=#{id}

如果我们使用,那么当传进来一个类型的时候我们需要使用{value},里面写id都是不可以的,必须写value

"selectStudentById" resultType="Student">
 select * from student where id=${value}

模糊查询的时候,以下方式是拼接的模式,容易被sql注入,所以我们一般不推荐:

<select id="selectStudentsByName" resultType="Student">
    
    select id,name,age,score from student where name like '%${value}%'
select>

注意不可以写成  '%#{name}%'  ,拼接的必须使用 $ 符号。可以使用函数进行连接:

"selectStudentsByName" resultType="Student">
    select id,name,age,score from student where name like concat('%',#{xxx},'%')

当然也可以不使用函数,注意 '%' 与 #{name} 之间是有空格的,要不会报错,这种是我们比较推荐的,也就是动态参数,可以极大减少sql注入的风险:

"selectStudentsByName" resultType="Student">
    select id,name,age,score from student where name like '%' #{name} '%'

【作者简介】
秦怀,公众号【秦怀杂货店】作者,技术之路不在一时,山高水长,纵使缓慢,驰而不息。这个世界希望一切都很快,更快,但是我希望自己能走好每一步,写好每一篇文章,期待和你们一起交流。

此文章仅代表自己(本菜鸟)学习积累记录,或者学习笔记,如有侵权,请联系作者核实删除。人无完人,文章也一样,文笔稚嫩,在下不才,勿喷,如果有错误之处,还望指出,感激不尽~

32cb04990e840f2f20b489a58a80df84.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值