自定义注解@MyBatisRepository

新建一个注解用作dao扫描

/**
 * @author fuguangli
 * @description 标识MyBatis的DAO,方便{@link org.mybatis.spring.mapper.MapperScannerConfigurer}的扫描。
 * @Create date:    2017/7/12
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Component
public @interface MybatisRepository {
    String value() default "";
}

2、配置bean,启动spring的时候扫描@MybatisRepository

<!-- 扫描basePackage下所有以@MyBatisDao注解的接口 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.qysxy"/>
        <property name="annotationClass" value="com.*****.annotation.MybatisRepository"/>
    </bean>

3、新建一个dao接口,并添加注解@MybatisRepository

/**
 * @author fuguangli
 * @description 
 * @Create date:    2017/3/14
 */
@MybatisRepository
public interface TestDao {

    List<TestData> findAllListed(TestData testData);
}

4、新建一个Mapper来实现dao接口

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.*****.TestDao">

    <sql id="columns">
    id,
    name
  </sql>
    <sql id="properties">
    #{id},
    #{name}
  </sql>
 <select id="findAllListed" resultMap="testDataResult" parameterType="TestData">
        SELECT *
        FROM test_test
        <where>
            <if test="id!=null and id!=0">
                and id=#{id}
            </if>
            <if test="name!=null and name!=‘‘">
               and name=#{name}
            </if>
        </where>
     </select>
</mapper>

6、测试

   @Autowired
    private TestDao testDao;

    @Test
    public void a1() {

        testDao.findAllListed(null);

    }
posted on 2018-12-07 23:23  花溪月影  阅读(4233)  评论(0编辑  收藏  举报