
先来简单回顾一下Mybatis的周期
-–FactoryBuilder—->Factory—->SqlSession—-Over
整合的第一步,导jar包,这里注意的是,一定要配置Maven静态资源的过滤问题,在这一步经常出问题。
解决方案:Invalid bound statement (not found)
要和 Spring 一起使用 MyBatis,需要在 Spring 应用上下文中定义至少两样东西:
- 一个SqlSessionFactory
- 至少一个数据映射器类。
FactoryBuilder直接交给spring接管,也就是说,需要给spring传入一个数据源
1 2 3 4 5 6 7 8 9
| <!--配置数据源:数据源有非常多,可以使用第三方的,也可使使用Spring的--> <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=true&useUnicode=true&characterEncoding=utf8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean>
|
当然,也可以使用默认的数据源
1 2 3 4 5 6 7 8 9 10
| <!--配置SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--关联Mybatis--> <property name="configLocation" value="classpath:mybatisconfig. xml"/> <property name="mapperLocations" value="classpath:com/kuang/dao/*.xml"/> </bean>
|
sqlsession也可以直接交给spring来接管,直接把之前的factory传入即可
(注意此时是c命名空间,因为SqlSessionTemplate这个类没有空参构造器)
1 2 3
| <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean>
|
就可以直接在dao层调了
1 2 3 4 5 6 7 8 9
| public class UserDaoImpl implements UserDao { private SqlSession sqlSession; public void setSqlSession(SqlSession sqlSession) { this.sqlSession = sqlSession; } public User getUser(String userId) { return sqlSession.getMapper...; } }
|
之后再bean中注册
1 2 3
| <bean id="userDao" class="com.wang.dao.UserDaoImpl"> <property name="sqlSession" ref="sqlSession"/> </bean>
|
然后就可以测试了
1 2 3 4 5 6 7 8
| @Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); UserMapper mapper = (UserMapper) context.getBean("userDao"); List<User> user = mapper.selectUser(); System.out.println(user); }
|