MyBatis 查询

Scroll Down

目录结构

image.png

创建表profile

image.png

在pojo包下创建实体类Profile

package com.buaoy.pojo;

public class Profile {
    private int personID;
    private String name;
    private String sex;
    private  String city;


    @Override
    public String toString() {
        return "Profile{" +
                "personID=" + personID +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", city='" + city + '\'' +
                '}';
    }
}

在Dao包下创建接口ProfileDao

  • 该接口提供一个返回Profile类列表的方法
public interface ProfileDao {
    List<Profile> selectProfileList();
}

配置UserMapper.xml

<?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.buaoy.Dao.ProfileDao">
    <select id="selectProfileList" resultType="com.buaoy.pojo.Profile">
select * from profile
</select>
</mapper>

绑定到mybatis-config.xml中(关键)

在mybatis-config.xml文件下添加

    <mappers>
        <mapper resource="com/buaoy/Dao/UserMapper.xml"/>
    </mappers>

如果不绑定就会出现以下错误
image.png

单元测试

在test/com/buaoy/Dao下创建一个ProfileDaoTest类用于测试

public class ProfileDaoTest {

    @Test
    public void Test(){
        SqlSession session = MyConnector.getSession(); // 获取一个连接数据库后得到的session
        ProfileDao profileDao = session.getMapper(ProfileDao.class);
        List<Profile> profileList = profileDao.selectProfileList();
        for(Profile profile:profileList){
            System.out.println(profile.toString());
        }
    }
}

运行结果

image.png