Spring 学习笔记 -
Part4 - Spring 整合MyBatis
学习资源来自B站黑马程序员:
https://www.bilibili.com/video/BV1Fi4y1S7ix/?p=20&share_source=copy_web&vd_source=c76bb3d6e0326c966bf1bf32db90eb22
XML方式实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilde();
InpiyStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
Account ac = accountDao.findById(2); System.out.printIn(ac);
sqlSession.close();
|
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; }
|