1、固定模板spring-dao.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置数据源,使用spring提供的数据源代替MyBatis-config.xml的配置,
这里使用spring的提供的jdbc-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/hu?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--SqlSessionFactory的配置-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--绑定mybatis配置文件-->
<property name="dataSource" ref="datasource"/>
<property name="configLocation" value="classpath:MyBatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/hu/mapper/*.xml"/>
</bean>
<!--sqlSessionTemplate需要一个参数,可以通过构造器注入参数有参构造,因为远吗中没有set方法-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
2、UserMapper.xml
<?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.hu.mapper.UserMapper">
<!--配置查询所有,id为查询的方法名称-->
<select id="findAll" resultType="com.hu.pojo.User">select * from hu.user;</select>
</mapper>
3、applicationContext.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.hu.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
</beans>
3、SqlSessionTemplate实现类
public class UserMapperImpl implements UserMapper{
//所有的操作原来都是使用sqlSession来执行,现在使用sqlSessionTemplate执行,二者类似
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
public List<User> findAll() {
UserMapper userMapper = sqlSessionTemplate.getMapper(UserMapper.class);
return userMapper.findAll();
}
}