1. 程式人生 > >Mybatis實現DAO層------------自動實現dao接口

Mybatis實現DAO層------------自動實現dao接口

cto nco autowire rep config rom public dao層 div

1、新建一個註解用作dao掃描

/**
 * @author fuguangli
 * @description 前沿mybatis掃描註解,此註解用於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,[email protected]

<!-- [email protected] -->
    <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接口,[email protected]

/**
 * @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);

    }

Mybatis實現DAO層------------自動實現dao接口