Mybatis查询示例

官网上面对mybatis入门示例介绍的很清楚了
https://mybatis.org/mybatis-3/zh/index.html

下面在idea中使用mybatis做个示例
整个流程图如下:


image.png

首先需要有个数据库表,在这里使用本地的learn库demo表

首先mybatis主配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/learn"/>
                <property name="username" value="root"/>
                <property name="password" value="jiahongtai"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="Demo.xml"/>
    </mappers>
</configuration>

想要得到的pojo类

public class Demo {
    int id;
    String name;

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

查询接口

public interface DemoDao {

    Demo selectById(int id);
    String selectByIdGetName(int id);

}

mapper配置文件

<?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="learnMybatis.DemoDao">
    <select id="selectById"  resultType="learnMybatis.Demo">
        select * from demo where id = #{id}
    </select>
    <select id="selectByIdGetName">
        select * from demo where id=#{id}
    </select>
</mapper>

注意:在maven下,不要将xml文件放到源目录下,在java目录下只会解析java文件,可以将xml放到resources目录下

测试main类

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 Main {
    public static void main(String[] args) throws IOException {
        String resource = "settings.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession session = sqlSessionFactory.openSession();
        DemoDao mapper = session.getMapper(DemoDao.class);
        Demo demo = mapper.selectById(1);
        System.out.println(demo);

    }
}

执行结果:


image.png
全部评论

相关推荐

头像
11-18 16:08
福州大学 Java
影流之主:干10年不被裁,我就能拿别人一年的钱了,日子有盼头了
点赞 评论 收藏
分享
Java抽象带篮子:难蚌,点进图片上面就是我的大头😆
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务