1.在lib 包中添加:
主要是添加多一个1.3的 mybatis-spring jar 包
2.pojo 实体类–>mapper—>config.xml—>mapper/IMP—>applicationContext.xml
其中 config.xml 中省略了连接数据库的操作,只需要保留typeAliases和mappers标签
3.mapper 中的 IMP
1)定义spring给mybatis提供的sqlsession对象:SqlSessionTemplate —> sqlsession
(private定义;public getter&setter )
2)SqlSessionTemplate.getMapper(AccountMapper.class)
3)返回方法
4.Service中的 IMP
1)private AccountMapper mapper;
2)重写方法并返回 mapper.findAll();
5.ApplicationContext.xml
顺序:
1.驱动管理数据源
2.sqlSessionFactoryBean
3.sqlSessionTemplate
4.AccountMapperIMP
5.AccountServiceIMP
<?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">
<!-- 1.驱动管理数据源 -->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="password" value="123"/>
<property name="username" value="root"/>
<property name="url" value="jdbc:mysql://localhost:3306/student?characterEncoding=utf8"/>
</bean>
<!-- 2.sqlsessionfatorybean -->
<bean id="sqlsessionfatorybean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="configLocation">
<value>classpath:mybatis-config.xml</value>
</property>
</bean>
<!-- 3.sqlsessionTemplate -->
<!--SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(sqlSessionFactoryBean)-->
<bean id="sqlsessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlsessionfatorybean"/>
</bean>
<!-- 4.AccountMapperImpl -->
<bean id="AccountMapperIMP" class="com.mapper.IMP.AccountMapperIMP">
<property name="sqlSessionTemplate" ref="sqlsessionTemplate"/>
</bean>
<!-- 5.AccountServiceImpl -->
<bean id="AccountServiceImpl" class="com.service.IMP.AccountServiceImpl">
<property name="mapper" ref="AccountMapperIMP"/>
</bean>
</beans>
6.Test类
// 1.ApplicationContext
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// 2.AccountServiceImpl
AccountServiceImpl service = (AccountServiceImpl) ac.getBean("AccountServiceImpl");
// 3.
List<Account> list = service.queryAccount();
for(Account account:list){
System.out.println(account);
}