spring-mybatis项目如何更简约地写daoimpl

如下,dao的impl中有大量重复且与业务无关语句,其实核心语句就一行sqlSession.selectOne("billDao.selectUser", uid);,我如何改进呢?

public UserDTO getUserByUid(int uid) {
        DBAccess dbAccess = new DBAccess();
        SqlSession sqlSession = null;
        UserDTO result = null;
        try {
            sqlSession = dbAccess.getSqlSession();
            result = sqlSession.selectOne("billDao.selectUser", uid);
            sqlSession.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(sqlSession != null) 
                sqlSession.close();
        }
            
        return result;
    }
阅读 6.8k
2 个回答

最好的做法自然是通过spring管理
如果要手动获取的session必然需要自己关闭.
一般来说使用spring-mybatis,如果要手动实现daoImpl,应该由spring注入由SqlSessionTemplate生成的sqlSession

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-arg index="0" ref="sqlSessionFactory" />
  <constructor-arg index="1" value="BATCH" />
</bean>
<bean id="xxDao" class="org.mybatis.spring.sample.dao.xxDaoImpl">
  <property name="sqlSession" ref="sqlSession" />
</bean>
SqlSession sqlSession;//通过spring注入
public UserDTO getUserByUid(int uid) {
      return result = sqlSession.selectOne("billDao.selectUser", uid);
    }

如果不手动实现daoImpl,可以编写Mapper接口,通过mybatis-spring提供的MapperFactoryBean类来动态代理实现mapper接口(即daoImpl)。

<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>
<bean id="userService" class="org.mybatis.spring.sample.mapper.UserServiceImpl">
  <property name="userMapper" ref="userMapper" />
</bean>

通过MapperFactoryBean动态实现接口注入业务层,则可以直接在业务层调用dao层的方法。

public class UserServiceImpl implements UserService {

  private UserMapper userMapper;

  public void setUserMapper(UserMapper userMapper) {
    this.userMapper = userMapper;
  }

  public User doSomeBusinessStuff(String userId) {
    return this.userMapper.getUser(userId);
  }
}```

使用spring-mybatis集成,写mapper即可

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题