1. package com.example.aninbatis.sqlsession;
    2. import com.example.aninbatis.config.Configuration;
    3. import com.example.aninbatis.config.MappedStatement;
    4. import com.example.aninbatis.executor.CachingExecutor;
    5. import com.example.aninbatis.executor.Executor;
    6. import com.example.aninbatis.executor.SimpleExecutor;
    7. import java.util.List;
    8. /**
    9. * 默认的sqlSession实现
    10. */
    11. public class DefaultSqlSession implements SqlSession {
    12. private Configuration configuration;
    13. public DefaultSqlSession(Configuration configuration) {
    14. this.configuration = configuration;
    15. }
    16. @SuppressWarnings("unchecked")
    17. @Override
    18. public <T> T selectOne(String statementId, Object param) {
    19. List<Object> list = this.selectList(statementId, param);
    20. if (list == null || list.size() == 0) {
    21. return null;
    22. } else if (list.size() == 1) {
    23. return (T) list.get(0);
    24. } else {
    25. throw new RuntimeException("只能返回一个对象");
    26. }
    27. }
    28. @Override
    29. public <T> List<T> selectList(String statementId, Object param) {
    30. // 根据statementId获取MappedStatement对象
    31. MappedStatement mappedStatement = configuration.getMappedStatementById(statementId);
    32. // 执行Statement的操作(执行方式有多种:一种是带有二级缓存的执行方式、一种是基本执行方式[只带有一级缓存,基本执行方式又分成几种:基本执行器、批处理执行器等])
    33. // 此处可以考虑放到MappedStatement对象中,该对象中可以根据是否配置了二级缓存来确定创建的是哪个Executor
    34. Executor executor = new CachingExecutor(new SimpleExecutor());
    35. return executor.query(mappedStatement, configuration, param);
    36. }
    37. }