自定義註解@MyBatisRepository

zhifeng687發表於2015-12-23

新建一個註解用作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);

    }



相關文章