Spring整合MyBatis
MyBatis提供了mybatis-spring.jar专门用于两大框架的整合。
①:第一步:
导入MyBatis整合Spring的相关坐标;
<!-- 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
public interface UserMapper { List<User> queryList(); }
<mapper namespace="com.hu.mapper.UserMapper"> <select id="queryList" > select * from user </select> </mapper>
③:第三步:
配置SqlSessionFactoryBean和MapperScannerConfigurer文章来源:https://www.toymoban.com/news/detail-640596.html
<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>
④:第四步:
编写测试代码文章来源地址https://www.toymoban.com/news/detail-640596.html
public void test02(){ ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml"); UserServiceImpl userService = applicationContext.getBean("userService", UserServiceImpl.class); userService.getUserList(); }
到了这里,关于Spring xml 方式整合mybatis 第三方框架的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!