1. 程式人生 > >Mybatis自定義註解實現DAO層--實現DAO層介面

Mybatis自定義註解實現DAO層--實現DAO層介面

  Java新增自定義註解:https://www.cnblogs.com/0xcafedaddy/p/6095187.html

1、自定義一個註解@MybatisRepository用作dao掃描

/**
 * @author cao
 * @description 前沿mybatis掃描註解,此註解用於org.mybatis.spring.mapper.MapperScannerConfigurer掃描
 * @Create date:    2018/11/14
 */
 @Retention(RetentionPolicy.RUNTIME)
 @Target(ElementType.TYPE)
 @Documented
 @Component
 public @interface MybatisRepository {
    String value() default "";
 }

2、配置bean,啟動spring的時候掃描@MybatisRepository

<!-- 掃描basePackage下所有以@MybatisRepository註解的介面 -->
    <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 cao
 * @description 
 * @Create date:    2018/11/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);

    }