Spring整合mybatis
1 . 导入Mybatis整合Spring的相关坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
2 . 编写Mapper和文件
在此给出 Mapper.xml文件如下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.UserMapper">
<select id="findAll" resultType="com.itheima.pojo.User">
select id,username,password from tb_user
</select>
</mapper>
3 . 在Applicationcontext.xml文件进行配置
<!-- 配置数据源信息-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"></property>
<property name="username" value="root"></property>
<property name="password" value="y2123802992"></property>
</bean>
<!--配置SqlSessionFactoryBean,作用将SqlSessionFactory存储到spring容器-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--MapperScannerConfigurer,作用扫描指定的包,产生Mapper对象存储到Spring容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.mapper"></property>
</bean>
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<!-- <constructor-arg name="name" value="haha"></constructor-arg> 构 造Bean的参数都可以这样设置-->
<property name="userMapper" ref="userMapper"></property>
</bean>
注意userMapper对象自动创建 , 由MapperScannerConfigurer扫描后,自动产生对象存储到Spring容器 , 所以无需配置 , 在userService标签里property属性直接设置即可
还需在userServiceiml里注入mapper
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
4 . 最后在测试文件测试即可
UserService bean = applicationContext.getBean(UserService.class);