前提

  • 在数据库中有一个表

    create table t1
    (
        id       int(16)     not null,
        name     varchar(32) not null,
        password char(32)    not null,
        constraint id
            unique (id)
    );
    
    alter table t1
        add primary key (id);

开始

1. 创建出与数据库数据对应的类

package com.example.mybatis;

public class t1Item {
    private int id;
    private String name;
    private String password;

    public t1Item(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public t1Item() {
    }

    @Override
    public String toString() {
        return "t1Item{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

2.创建一个Mapper接口

public interface t1Mapper {
    public List<t1Item> getAll();
}

3. 创建Mapper接口对应的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.example.mybatis.t1Mapper">
    <select id="getAll" resultType="com.example.mybatis.t1Item">
        select * from t1 ;
    </select>
</mapper>

4. 测试

@Test
	void contextLoads() throws IOException {
		SqlSessionFactory sessionFactory = SessionFactory.getSessionFactory();
		try (SqlSession session = sessionFactory.openSession()) {
			t1Mapper mapper = session.getMapper(t1Mapper.class);
			mapper.getAll().forEach(System.out::println);
		}
	}

5. 结果

t1Item{id=1, name='a1', password='1234'}
t1Item{id=2, name='a2', password='123445'}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!

传递Map类型参数 上一篇
传递自定义对象类型参数 下一篇