MyBatis访问MySQL数据库主要流程

连接数据库分为六步

package com.leo;

import com.leo.dao.ICardMapping;
import com.leo.entity.Card;
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;
import java.util.List;

/** * @ClassName: Main * @Author: Leo * @Description: * @Date: 2019/5/5 14:21 */
public class Main {
    static final String res = "mybatis-config.xml";

    public static void main(String[] args) throws IOException {
        //1.读取配置文件
        InputStream config = Resources.getResourceAsStream(res);
        //2.创建sqlSessionFactory
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(config);
        //3.开启sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4.获取操作接口
        ICardMapping iCardMapping = sqlSession.getMapper(ICardMapping.class);
        //5.访问数据库
        List<Card> cards = iCardMapping.getAllCard();
        for (Card card : cards) {
            System.out.println(card);
        }
        //6.关闭资源
        sqlSession.close();
        config.close();
    }
}

输出结果

全部评论

相关推荐

Natrium_:这时间我以为飞机票
点赞 评论 收藏
分享
牛客5655:其他公司的面试(事)吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务