java - spring-mybatis项目如何更简约地写daoimpl
伊谢尔伦
伊谢尔伦 2017-04-17 16:05:53
[Java讨论组]

如下,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;
    }
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(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);
  }
}```
PHPz

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号