Getting start
Mybatis整合Spring必须要做的两件事:在spring application context里定义一个SqlSessionFactory 和至少一个映射类.例如:
这里应当注意SqlSessionFactory 需要一个数据源。这个数据源可以是任何符合spring配置的数据连接
假设有一数据映射类如下:
- public interface UserMapper {
- @Select("SELECT * FROM users WHERE id = #{userId}")
- User getUser(@Param("userId") String userId);
- }
- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
- <property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
- <property name="sqlSessionFactory" ref="sqlSessionFactory" />
- </bean>
现在调用映射类方法只需一行代码:
- public class FooServiceImpl implements FooService {
- private UserMapper userMapper;
- public void setUserMapper(UserMapper userMapper) {
- this.userMapper = userMapper;
- }
- public User doSomeBusinessStuff(String userId) {
- return this.userMapper.getUser(userId);
- }
- }