Spring 学习笔记 - Part4 - Spring 整合MyBatis

学习资源来自B站黑马程序员: https://www.bilibili.com/video/BV1Fi4y1S7ix/?p=20&share_source=copy_web&vd_source=c76bb3d6e0326c966bf1bf32db90eb22

XML方式实现

  • MyBatis程序核心对象分析
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//1.创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilde();
//2.加载SqlMapConfig.xml配置文件
InpiyStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//3.创建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
/*初始化SqlSessionFactroy*/
//4.获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//5.执行SqlSession对象执行查询,获取结果User
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
/*获取实现*/
Account ac = accountDao.findById(2);
System.out.printIn(ac);
/*获取数据层接口*/
//6.释放资源
sqlSession.close();
/*关闭连接*/
  • 整合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
<configuration>
<!--初始化属性数据-->
<properties resource="jdbc.properties"></properties>
<!--初始化类型别名-->
<typeAliases>
<package name="com.itheima.domain"/>
</typeAliases>
<!--初始化dataSource-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"> <dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</transactionManager>
</environment>
</environments>
<!--初始化映射配置-->
<mappers>
<package name="com.itheima.do"></package>
</mappers>
</configuration>

注解方式实现

  • 注册SqlSessionFactoryBean类,并配置数据库
1
2
3
4
5
6
7
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactryBean ssfb = new SqlSessionFactoryBean();
ssfb.setTypeAliasePackage("com.hcx.pojo");
ssfb.setDataSource(dataSource);
return ssfb;
}
  • 配置映射包
1
2
3
4
5
6
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.hcx.dao");
return msc;
}