Spring學習筆記——第十一部分 整合MyBatis
阿新 • • 發佈:2021-01-15
技術標籤:Spring學習筆記mybatisspringjavamysql
Spring學習筆記——第十一部分 整合MyBatis
1. 步驟
- 匯入jar包
- 編寫配置檔案
- 測試
2. MyBatis-Spring
- 編寫資料來源
<!--DataSource:使用Spring的資料來源替換MyBatis的配置
我們這裡使用Spring提供的JDBC:org.springframework.jdbc.datasource-->
<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/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
- sqlSessionFactory
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--繫結MyBatis配置檔案-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath*:com/zhang/mapper/*.xml"/>
</bean>
- sqlSessionTemplate
<!--SqlSessionTemplate:就是我們使用的SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
- 給介面加一個實現類
public class UserMapperImpl implements UserMapper{
//原來,我們的所有操作,都使用sqlSession執行
//現在使用sqlSessionTemplate
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
- 測試
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}