SqlSessionFactory是mybatis的基础中的基础,必须实例!
逻辑思路:
- 减少代码冗余,需要封装mybatisAPI。
- 可以注册SqlSessionFactoryBean,来完成SqlSessionFactory的实例化。
它的实例化需要(依赖)"mybatis-config.xml"文件,
其中有三大抽象:1、数据源;2、别名;3、注册mapper
可以把依赖(作为属性)注入(DI)到SqlSessionFactoryBean中,
来完成SqlSessionFactory的实例化。
pom:junit、webmvc、mysql-connector、spring-jdbc、mybatis、mybatis-spring、lombok
1、spring-dao.xml:bean约束
|
1
2
3
4
5
6
7
8
|
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
|
2、db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库?serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=123
3、引入数据库配置文件
<context:property-placeholder location="classpath:db.properties"/>
4、从spring自带jdbc配置数据源
|
1
2
3
4
5
6
|
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
|
5、利用SqlSessionFactoryBean获取配置SqlSessionFactory实例
|
1
2
3
4
5
|
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath*:mapper/*.xml"/>
<property name="typeAliasesPackage" value="pojo"/>
</bean>
|
6、扫描dao包,同时生成sqlsessionTemplate和注入mapper接口的实现类
|
1
2
3
4
|
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
|
7、加载spring-dao.xml获取上下文,从而为dao接口自动装配
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/spring-dao.xml");
StudentDao studentDao = (StudentDao) context.getBean("studentDao");
List<Student> students = studentDao.selectAll();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
原文链接:https://www.cnblogs.com/mo-jian-ming/p/13285996.html
相关文章
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-05-26 102
-
2025-05-25 81
-
2025-06-04 70
-
2025-05-27 27
-
2025-06-04 51

