环境说明
通过SpringIOC框架整合Mybatis访问MySQL数据库
JDK环境1.8. Spring和Mybatis版本如下图JAR包所示,需要注意的是,JDK版本最低为1.8,最高不要超过10. 否则会报版本错误。
用到的JAR包:
其实用不到这么多,但是为了之后项目的方便这里把会用到的都加上了。
如果需要这些JAR包可以在下面留言。
SpringIOC配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- dataSource的bean对象,用来配置连接数据库的基础信息-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?verifyServerCertificate=false&useSSL=false&serverTimezone=UTC"></property>
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>
<!--配置SqlSession的bean对象,生产SqlSession-->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置Mapper扫描的bean对象,获取Mapper接口的实例对象-->
<bean id="Mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="factory"></property>
<property name="basePackage" value="com.erwin.mapper"></property>
</bean>
<!--MapperScannerConfigurer对象会根据 basePackage的路径自动扫描其下的mapper接口/对象,并自动重建mapper对象,会将其首字母自动小写
</beans>
Mapper接口
该mapper接口放在com.erwin.mapper路径下,对应上述代码段中的<property name="basePackage" value="com.erwin.mapper">
,之后SpringIOC会自动扫描其下所有文件
package com.erwin.mapper;
import org.apache.ibatis.annotations.Select;
public interface Mapper {
@Select("select count(*) from student")
int getFromStudent();
//直接使用@注解方式来访问数据库
}
调用Mapper层Bean对象,并直接调用方法
public abstract class test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//从Spring容器对象获取业务层对象
String[] names = ac.getBeanDefinitionNames();
for(String str : names){
System.out.println(str);
}
Mapper mapper = (Mapper)ac.getBean("mapper");
System.out.println(mapper.getFromStudent());
}
}
这段代码分为两个部分
String[] names = ac.getBeanDefinitionNames();
for(String str : names){
System.out.println(str);
}
是用来查看现在SpringIOC创建了哪些Bean对象,便于我们解析Spring的工作情况。
如图,除了我们自己配置的ID为Mapper的对象之外,Spring还自动为我们创建了mapper对象,这个对象实际上是上述Mapper接口的实例化对象。
下一段代码调用了我们在Mapper接口中用注解方式实现的方法:
Mapper mapper = (Mapper)ac.getBean("mapper");
System.out.println(mapper.getFromStudent());