当spring与mybatis整合时,mybatis中的配置数据库连接环境的配置文件可以去掉,因为里面的配置可以直接在spring的配置文件中配置,类BasicDataSource是封装的一个类,用来配置数据库连接环境,我用的是读取小配置文件的方式,获取参数,属性名一定不能写错了
<context:property-placeholder location="classpath:/datasource.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${user}"></property>
<property name="password" value="${password}"></property>
</bean>
类SqlSessionFactoryBean充当SqlSessionFactory,属性“typeAliasesPackage”,value的值为包名,达到为此包下的类起别名的作用,此包下的所有实体类的别名为实体类类名的首字母小写,列如:entity.Student这个类的别名为student,属性“mapperLocations”指定mybatis中映射文件的路径可以使用通配符*,“*mapper.xml”是指所有以“mapper.xml”结尾的文件
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage">
<value>entity</value>
</property>
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="mapperLocations">
<list>
<value>mapper.xml</value>
</list>
</property>
</bean>
在mybatis中我们用SqlSession工具类获得dao层接口的实现类对象,而在spring和mybatis整合中,MapperScannerConfigurer将扫描basePackage所指定的包下的所有接口类(包括子类),如果它们在SQL映射文件中定义过,则将它们动态定义为一个Spring Bean,可以通过接口名首字母小写作为bean id获得接口实现类
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage">
<value>dao</value>
</property>
</bean>
测试类
public class StudentTest {
@Test
public void Test1() {
ApplicationContext ac=new ClassPathXmlApplicationContext("/applicationContext.xml");
StudentDAO dao=(StudentDAO) ac.getBean("studentDAO");
Student s=dao.queryById(1);
System.out.println(s);
}
}