MyBatis-Plus动态返回实体类

玩技站长 科技百科评论127字数 490阅读1分38秒阅读模式
摘要// may have fetched a connection so let's call close()...
1. 自定义sqlSession
@Slf4j
public class GenericsqlSession extends DefaultsqlSession {
    private static final ThreadLocal<Class<?>> CTX = new ThreadLocal<>();
    private final Executor generalExecutor;
    public GenericsqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
        super(configuration, executor, autoCommit);
        this.generalExecutor = executor;
    }
    @Override
    public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
        return doSelectList(statement, parameter, rowBounds);
    }
    protected <E> List<E> doSelectList(String statement, Object parameter, RowBounds rowBounds) {
        try {
            return generalExecutor.query(getCustomMappedStatement(statement),
                    ParamNameResolver.wrapToMapIfCollection(parameter, null), rowBounds, Executor.NO_RESULT_HANDLER);
        } catch (Exception e) {
            throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
    }
    protected MappedStatement getCustomMappedStatement(String statement) {
        var ms = getConfiguration().getMappedStatement(statement);
        var clazz = GenericsqlSession.get();
        if (ObjectUtil.isEmpty(clazz)) {
            return ms;
        } else {
            var resultMaps = ms.getResultMaps();
            var resultMap = resultMaps.get(0);
            var customMap = new ResultMap.Builder(getConfiguration(), resultMap.getId(),
                    clazz, resultMap.getResultMappings(), resultMap.getAutoMapping()).build();
            return new MappedStatement.Builder(getConfiguration(), ms.getId(), ms.getsqlSource(), ms.getsqlCommandType())
                    .resultMaps(Collections.singletonList(customMap))
                    .resource(ms.getResource())
                    .useCache(ms.isUseCache())
                    .build();
        }
    }
    public static void set(Class<?> clazz) {
        CTX.set(clazz);
    }
    public static Class<?> get() {
        return CTX.get();
    }
    public static void remove() {
        CTX.remove();
    }
}

2. 自定义sqlSessionFactory 文章源自玩技e族-https://www.playezu.com/744994.html

public class GenericsqlSessionFactory extends DefaultsqlSessionFactory {
    public GenericsqlSessionFactory(Configuration configuration) {
        super(configuration);
    }
    @Override
    public sqlSession openSession(ExecutorType execType) {
        Transaction tx = null;
        try {
            final var environment = getConfiguration().getEnvironment();
            final var transactionFactory = getTransactionFactoryFromEnvironment(environment);
            tx = transactionFactory.newTransaction(environment.getDataSource(), null, false);
            final var executor = getConfiguration().newExecutor(tx, execType);
            return new GenericsqlSession(getConfiguration(), executor, false);
        } catch (Exception e) {
            // may have fetched a connection so let's call close()
            closeTransaction(tx);
            throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
    }
    private TransactionFactory getTransactionFactoryFromEnvironment(Environment environment) {
        if (environment == null || environment.getTransactionFactory() == null) {
            return new ManagedTransactionFactory();
        }
        return environment.getTransactionFactory();
    }
    private void closeTransaction(Transaction tx) {
        if (tx != null) {
            try {
                tx.close();
            } catch (sqlException ignore) {
                // Intentionally ignore. Prefer prevIoUs error.
            }
        }
    }
}

3. 自定义sqlSessionTemplate 文章源自玩技e族-https://www.playezu.com/744994.html

@Component
public class GenericsqlSessionTemplate extends sqlSessionTemplate {
    public GenericsqlSessionTemplate(sqlSessionFactory sqlSessionFactory) {
        super(new GenericsqlSessionFactory(sqlSessionFactory.getConfiguration()));
    }
}

4. 自定义基础Mapper 文章源自玩技e族-https://www.playezu.com/744994.html

public interface SuperMapper<T> extends BaseMapper<T> {
    /**
     * selectById
     *
     * @param clazz 自定义结果集class
     * @param id    id
     * @param <D>   D
     * @return D
     */
    @SuppressWarnings("unchecked")
    default <D> D selectById(Class<D> clazz, Serializable id) {
        try {
            GenericsqlSession.set(clazz);
            return (D) selectById(id);
        } finally {
            GenericsqlSession.remove();
        }
    }
}

5. 使用 文章源自玩技e族-https://www.playezu.com/744994.html

继承自定义的基础Mapper文章源自玩技e族-https://www.playezu.com/744994.html

@Data
@TableName("tag")
public class TagPO implements Serializable {
    private static final long serialVersionUID = 1L;
    @TableId(type = IdType.AUTO)
    private Integer id;
    private String name;
}
public interface TagDAO extends SuperMapper<TagPO> {
}
@Component
@Slf4j
public class MybatisTest implements CommandLineRunner {
    @Autowired
    TagDAO tagDAO;
    @Override
    public void run(String... args) throws Exception {
        TagDTO id1 = tagDAO.selectById(TagDTO.class, 1);
        log.info("{}", id1);
        TagPO id2 = tagDAO.selectById(1);
        log.info("{}", id2);
    }
}

原文地址:https://cloud.tencent.com/developer/article/2051306文章源自玩技e族-https://www.playezu.com/744994.html

文章源自玩技e族-https://www.playezu.com/744994.html文章源自玩技e族-https://www.playezu.com/744994.html
 
匿名

发表评论

匿名网友
确定

拖动滑块以完成验证