美文网首页
通用Mapper Spring Mvc

通用Mapper Spring Mvc

作者: 沉思的老猫 | 来源:发表于2017-11-27 15:45 被阅读0次

项目地址:https://github.com/mybatis/mybatis-3.git
1、使用
添加Maven依赖

<!-- Spring Mvc使用 -->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper</artifactId>
    <version>最新版本</version>
</dependency>

TestExampleMapper

public interface TestExampleMapper extends Mapper<TestExample> {
}

实体类注解

public class TestExample {
    @Id
    private Integer id;
    @Column
    private String  name;
    private String logo;
    //省略setter和getter方法
}

简单用法示例

@Resource
private TestExampleMapper  mapper;

Condition condition = new Condition(TestExample .class);
condition .createCriteria().andGreaterThan("id", 100);
List<TestExample > exampleList = mapper.selectByCondition(condition );

spring 配置

<!-- Mybatis 配置-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource"/>
      <property name="configLocation" value="classpath:conf/mybatis-config.xml"/>
      <!-- 配置mapper.xml文件所在位置-->
      <property name="mapperLocations" value="classpath*:mapper/**/*.xml"/>
      <!-- 需要启动别名model所在包位置 -->
      <property name="typeAliasesPackage" value="com.orm.model,com.common.dto"/>
      <!--mybatis插件配置-->
      <property name="plugins">
          <array>
              <bean class="com.github.pagehelper.PageHelper">
                  <property name="properties">
                      <value>
                          dialect=mysql
                      </value>
                  </property>
              </bean>
          </array>
      </property>
</bean>
<!--使用通用Mapper 重写的 MapperScannerConfigurer-->
 <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.orm.mapper"/>
        <property name="properties">
            <value>
                mappers=com.orm.Mapper
            </value>
        </property>
    </bean>

2、自定义

import tk.mybatis.mapper.common.BaseMapper;
import tk.mybatis.mapper.common.ConditionMapper;
import tk.mybatis.mapper.common.IdsMapper;
import tk.mybatis.mapper.common.special.InsertListMapper;

//定制接口
public interface Mapper<T>
        extends
        BaseMapper<T>,
        ConditionMapper<T>,
        IdsMapper<T>,
        InsertListMapper<T> {
}

//引用
@Autowired
protected Mapper<T> mapper;
//调用InsertListMapper的insertList方法
public void save(T model){
  mapper.insertList(models);
}

//tk的InsertListMapper接口源码
public interface InsertListMapper<T> {
    @Options(
        useGeneratedKeys = true,
        keyProperty = "id"
    )
    @InsertProvider(
        type = SpecialProvider.class,
        method = "dynamicSQL"
    )
    int insertList(List<T> var1);
}

相关文章

网友评论

      本文标题:通用Mapper Spring Mvc

      本文链接:https://www.haomeiwen.com/subject/tlpfbxtx.html