yangyang12138

导航

mybatis

1.概述

  本文主要演示如何使用代码直接使用mabatis而不是通过spring配置,mybatis本身就是一个拼sql都工具,xml里实现了多种sql表达式。

2.实现

     this.configuration = new Configuration();

        SqlSource raw = new XMLLanguageDriver().createSqlSource(configuration,"select * from ${srcTable} where id=#{id})",Map.class);

        MappedStatement.Builder mb = new MappedStatement.Builder(configuration,"mdata",raw, SqlCommandType.SELECT);

        List<ResultMap> resultMaps = new ArrayList<ResultMap>();

        resultMaps.add(new ResultMap.Builder(configuration,"mdataMap", Map.class,new ArrayList<ResultMapping>()).build());

        mb.resultMaps(resultMaps);

        MappedStatement mappedStatement = mb.build();

        configuration.addMappedStatement(mappedStatement);

        configuration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);

调用时只需sqlSession.selectList("mdata")

mdata本质上只是id,如果是想使用mapper,只需将id定义为 全类名.方法名的形式

 

package com.demo;
public interface UserMapper{

      Map<String,String> test(Integer id);    

}
MappedStatement.Builder mb = new MappedStatement.Builder(configuration,"com.demo.UserMapper.test",raw, SqlCommandType.SELECT);

sqlSession.createMapper(UserMapper.class).test(1);

posted on 2022-09-21 01:09  杨杨09265  阅读(14)  评论(0编辑  收藏  举报