mybatis文件映射之select操作返回List集合


在EmplyeeMapper.java中:

public List<Employee> getEmpByLastNameLike(String lastName);

在EmployeeMapper.xml中

    <select id="getEmpByLastNameLike" resultType="com.gong.mybatis.bean.Employee">
        select id,last_name lastName,gender,email from tbl_employee where last_name like #{lastName}
    </select>

由於數據庫中的字段last_name與實體類中的lastName名字不對應,因此需要用別名來指代。

之后進行單元測試:

package com.gong.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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 org.junit.Test;

import com.gong.mybatis.bean.Employee;
import com.gong.mybatis.dao.EmployeeMapper;
import com.gong.mybatis.dao.EmployeeMapperAnnotation;

public class TestMybatis {
    
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream is = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(is);
    }

    @Test
    public void test04() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            List<Employee> employees = mapper.getEmpByLastNameLike("%小%");
            for(Employee e:employees) {
                System.out.println(e);
            }
            openSession.commit();
        } finally {
            openSession.close();
        }
        
    }

}

補充:進行模糊查詢時:

 1. LIKE'Mi%' 將搜索以字母 Mi開頭的所有字符串(如 Michael)。

 2. LIKE'%er' 將搜索以字母 er 結尾的所有字符串(如 Worker、Reader)。

 3. LIKE'%en%' 將搜索在任何位置包含字母 en 的所有字符串(如 When、Green)。

在數據庫中的數據為:

執行test04方法,得到:

至此結合List進行select操作的流程就基本完成了。 需要注意的若返回值是List集合,在mapper.xml文件中返回值的類型是集合里面的類的類型。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM