spring与Mybatis整合,即mybatis相关的Bean交给spring容器来管理
mybatis核心的类是SqlSessionFactory通过该类可以过去SqlSession对象完成对数据库的增删改查操作
Spring与Mybatis的环境搭建
Spring与Mybatis整合的jar包是由Mybatis提供的
Mybatis环境搭建:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.abc.beans"/>
</typeAliases>
<mappers>
<package name="com.abc.dao"/>
</mappers>
</configuration>
- 在Dao包下创建与Dao接口名一致的映射文件,名称空间为接口的全名
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.abc.dao.StudentDao">
<insert id="insertStudent">
insert into student(name,age) values(#{name}, #{age})
</insert>
<delete id="deleteStudentById">
delete from student where id=#{xxx}
</delete>
<update id="updateStudent">
update student set name=#{name}, age=#{age} where id=#{id}
</update>
<select id="selectStudentById" resultType="Student">
select id,name,age from student where id=#{xxx}
</select>
<select id="selectAllStudents" resultType="Student">
select id,name,age from student
</select>
</mapper>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test
jdbc.user=root
jdbc.password=123
Spring容器的配置:
- 导入数据源的jar包(c3p0或dbcp,我使用的是c3p0)
- 在spring容器中注册ComboPooledDataSource,引入jdbc的属性文件
<!-- 注册DataSource:C3P0 -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<context:property-placeholder location="jdbc.properties"/>
- 也可以用c3p0-config.xml配置文件,如果使用该配置文件,那么在spring容器中不需要对c3p0进行属性注入,修改配置文件即可
- 通过SqlSessionFactroyBean生成SqlSessionFactory
<!-- 生成SqlSessionFactory -->
<bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="configLocation" value="mybatis.xml"/>
</bean>
- 得到SqlSessionFactory以后我们需要有Dao对象才能调用类中的方法
- 生成Dao的方法有好几种,我这里介绍一下比较常用的两种
- 通过MapperFactoryBean生成Dao
<!-- 生成Dao -->
<bean id="studentDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="mySqlSessionFactory"/>
<property name="mapperInterface" value="com.abc.dao.IStudentDao"/>
</bean>
<!-- 生成Dao -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="mySqlSessionFactory"/>
<property name="basePackage" value="com.abc.dao"/>
</bean>