1、读取配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
2、获取SqlSessionFactory SqlSessionFactiryBuilder builder = new
SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.builder(reader);
3、获取SqlSession
SqlSession session = factory.openSession();
//System.out.println(session.getConnection());
4、基于AccountDao 完成对应实现类对象的创建,
// AccountDao 是接口,不能完成对象创建;AccountDaoMapper.xml替换实现类
AccountDao dao = session.getMapper(AccountDao.class); // AccountDao dao =
new AccountDaoImpl();
Account acc = dao.queryOneById(21);
System.out.println(acc);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
例:
public class TestAccountDao {
public static void main(String[] args) throws IOException {
//1、读取配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
//2、获取SqlSessionFactory
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(reader);
//3、获取SqlSession
SqlSession session = factory.openSession();
// System.out.println(session.getConnection());
//4、基于AccountDao 完成对应实现类对象的创建。
//AccountDao 是接口,不能完成对象的创建:AccountDaoMapper.xml 替换实现类
AccountDao dao = session.getMapper(AccountDao.class);
//理解为AccountDao dao = new AccountDaoImpl();
//通过 builder
Account acc = dao.selectOneById(2);
System.out.println(acc);
// @Test
// public void testSelectById() throws IOException{
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24