Mybatis整合Spring
Spring整合MyBatis其实就是Spring通过jar包中的类对应Mybatis全局配置文件通过组件的方式将其交给Spring容器管理的过程;
一:数据源
二:使用数据源创建SqlSessionFactory
三:扫描mapper并和sqlSessionFactory产生关联
HelloWord:只是最基础的能跑起来;
<?xml version="1.0" encoding="UTF-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"> <!--配置数据源--> <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="username" value="root"/> <property name="password" value="root"/> <property name="url" value="jdbc:mysql:///test"/> </bean> <!--使用数据源创建sqlSessionFactory--> <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactory"> <!--创建sqlSession需要有数据库连接,na那么就引用上边的数据源--> <property name="dataSource" ref="dataSource"/> </bean> <!--扫描器,加载mapper文件--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.xpl.mapper"/> <!--之前我们是--> <!--InputStream is = Resources.getResourceAsStream("mybatis-conf.xml");--> <!--SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);--> <!--这样加载的mybatis配置文件,然后将is放进了SqlSessionFactory--> <!--is中包含了扫描进来的mapper.xml--> <!--所以SqlSessionFactory中包含了扫描进来的mapper.xml--> <!--所以在这里我们要让sqlSessionFactory和Mapper产生关系--> <!--将上边的sessionFactory注入进来--> <property name="sqlSessionFactory" ref="sessionFactory"/> </bean> </beans>
<mapper namespace="com.xpl.mapper.UserMapper"> <select id="selAllUser" resultType="com.xpl.model.User"> select * from user; </select> </mapper>
package com.xpl.test; import com.xpl.impl.UserMapperImp; import com.xpl.mapper.UserMapper; import com.xpl.model.User; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class Test { public static void main(String[] args) { ClassPathXmlApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext.xml"); // String[] names = cxt.getBeanDefinitionNames(); // for(String s:names){ // System.out.println(s); // // 打印结果: // dataSource // sessionFactory // org.mybatis.spring.mapper.MapperScannerConfigurer#0 // userMapper // 发现已经有userMapper这个bean了 // 直接去get到这个Bean然后去执行selAllUser() // } UserMapper bean = cxt.getBean(UserMapper.class); List<User> users1 = bean.selAllUser(); System.out.println(users1); } }