Spring整合MyBatis
MyBatis提供了mybatis-spring.jar专门用于两大框架的整合。
①:第一步:
导入MyBatis整合Spring的相关坐标;
XML<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>3.0.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.29</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.18</version> </dependency>
②:第二步:
编写Mapper和Mapper.xml
javapublic interface UserMapper { List<User> queryList(); }
XML<mapper namespace="com.hu.mapper.UserMapper"> <select id="queryList" > select * from user </select> </mapper>
③:第三步:
配置SqlSessionFactoryBean和MapperScannerConfigurer
XML<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/test"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean> <!--将sqlsession对象配置到spring容器中--> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <!--想连接数据 需要配置datasoure数据源 注入数据源--> <property name="dataSource" ref="dataSource"></property> </bean> <!--将com.hu.mapper下面xml配置文件生成的对象放到spring容器中--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.hu.mapper"/> </bean> <!--将service对象注入到spring中--> <bean id="userService" class="com.hu.service.impl.UserServiceImpl" > <property name="userMapper" ref="userMapper"></property> </bean>
④:第四步:
编写测试代码
javapublic void test02(){ ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml"); UserServiceImpl userService = applicationContext.getBean("userService", UserServiceImpl.class); userService.getUserList(); }