Mybatis快速入门

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class MybatisDemo {
public static void main(String[] args) throws IOException {

// 1.加载mybatis核心配置文件,获取SqlSessionFactory Mybatis官方网站有
String resource = "mybatis-config.xml";//mybatis相对路径
//获取inputStream通过Resources对象(资源加载类)getResourceAsStream(resource)将字符串传进来 返回一个字节输入流
InputStream inputStream = Resources.getResourceAsStream(resource);
//通过SqlSessionFactoryBuilder()对象的build()方法将流传进来返回SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

// 2.获取SqlSessionFactory对象 执行sql语句
SqlSession session = sqlSessionFactory.openSession();

// 3.执行sql语句
//session.selectOne()
//session.selectList("test.selectAll");
List<User> users = session.selectList("MapperDemo.selectAll");
System.out.println(users);

// 4.释放资源
session.close();

}
}