获取SqlSessionFactory
利用sqlSessionFactory获取sqlSession
sql操作
sqlSession.selectOne()
sqlSession.selectList()
sqlSession.update()
sqlSession.delete()
创建mapper接口
获取SqlSessionFactory
测试时 利用sqlSessionFactory获取sqlSession
sqlSession.getMapper(UserMapper.class) 生成接口的实现类
sql操作 (使用UserMapper接口中定义的方法)
userMapper.findUserById()
userMapper.listUser()
userMapper.update()
userMapper.delete()
在spring中配置SqlSessionFactoryBean 含有两个属性
<bean id="sqlSessionFactory" class="com.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean>
实现userDao接口
class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{ public User findUserById(Integer id){ return this.getSqlSession().selectOne("com.tyut.mapper.findUserById",id); } }
在配置文件中配置 userDao
<bean id="userDao" class="com.tyut.Dao.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>测试时,通过applicationContext.getBean==(UserDao.class)==;获取userDao
操作sql
userDao.findUserById()userDao.listUser()userDao.update()userDao.delete()与上述第一步相同 定义SqlSessionFactory
只定义UserMapper接口不需要手动实现
在spring配置文件中利用MapperFactoryBean实现UserMapper接口
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.tyut.mapper.UserMapper" /> <property name="sqlSessionFactory" ref="sqlSession"/> </bean>测试时,通过applicationContext.getBean==(UserMapper.class)==;获取userMapper
操作sql
userMapper.findUserById()userMapper.listUser()userMapper.update()userMapper.delete()注意
当有多个mapper接口时需要在spring中配置多个MapperFactoryBean,而下方扫描的不需要
与上述第一步相同 定义SqlSessionFactory
只定义UserMapper接口不需要手动实现
在spring配置文件中利用
<bean class="org.mybatis.spring.mapper.MaperScanConfigurer"> <property name="basepackage" value="com.tyut.mapper" /> </bean>或者使用
<mybatis-spring:scan base-package="com.tyut.mapper" />测试时,通过applicationContext.getBean(UserMapper.class);获取userMapper
操作sql
userMapper.findUserById()userMapper.listUser()userMapper.update()userMapper.delete()