mybatis 操作数据库方式
(一)spring与mybatis整合之前
-
mybatis最基本的用法(需要写mappers)
-
获取SqlSessionFactory
-
利用sqlSessionFactory获取sqlSession
-
sql操作
-
sqlSession.selectOne()
-
sqlSession.selectList()
-
sqlSession.update()
-
sqlSession.delete()
-
-
使用mapper接口 (需要写 mappers)
-
创建mapper接口
-
获取SqlSessionFactory
-
测试时 利用sqlSessionFactory获取sqlSession
-
sqlSession.getMapper(UserMapper.class) 生成接口的实现类
-
sql操作 (使用UserMapper接口中定义的方法)
-
userMapper.findUserById()
-
userMapper.listUser()
-
userMapper.update()
-
userMapper.delete()
-
(二)整合之后
-
-
spring与mybatis整合 传统的Dao开发==(此种方式还需要在mybatis-config.xml中加载mapper.xml文件)== (需要写mappers)
-
在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()
-
-
spring与mybatis利用MapperFactoryBean整合 ,在mybatis-confi.xml可以不定义mappers
-
与上述第一步相同 定义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,而下方扫描的不需要
-
-
spring与mybatis利用MapperScanConfigurer,在mybatis-config.xml中可以不定义mappers
-
与上述第一步相同 定义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()
-