天天看點

1. Mybatis入門程式提示找不到XxxDao.xml配置檔案

  • 【問題】Mybatis入門程式提示找不到XxxDao.xml配置檔案

    【解決方案】resources/XxxMapper.xml配置檔案所在的包必須與java/XxxMapper.java所在的包結構相同

    注意:在resources中建立檔案夾的時候隻能用dictionary,此時需要一級一級建立,否則建立出來的是一級檔案夾

    packging建立時: com.hqing.dao是三級結構

    dictionary建立時: com.hqing.dao是一級結構

  • Mybatis環境搭建:

    ① 建立工程,添加依賴

<dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
           

② 建立實體類和dao接口

③ 建立Mybatis主配置檔案 SqlMapConfig.xml

添加限制條件—

configuration

配置mysql環境— 指定映射配置檔案位置(每個dao獨立的配置檔案)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- Mybatis主配置檔案-->
<configuration>
    <environments default="mysql">
        <environment id="mysql">
            <!--配置事務類型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置資料源(連接配接池)-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/hiqing1_demo"/>
                <property name="username" value="。。。。"/>
                <property name="password" value="。。。。。。"/>
            </dataSource>
        </environment>
    </environments>
    
    <!-- 指定映射配置檔案的位置(每個獨立mapper的配置檔案)-->
    <mappers>
        <mapper resource="com/september/dao/IUserDao.xml"></mapper>
    </mappers>
</configuration>
           

④ 建立映射配置檔案IUserDao.xml

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.september.dao.IUserDao">
    <!--配置查詢所有-->
    <select id="findAll" resultType="com.september.domain.User">
        select * from user
    </select>
</mapper>
           

– mybatis的映射配置檔案位置必須和dao接口的包結構相同

– 映射配置檔案的mapper标簽namespace屬性的取值必須是dao接口的全限定類名

– 映射配置檔案的操作配置(select),id屬性的取值必須是dao接口的方法名

– 在映射配置中告知mybatis要封裝到哪個實體類中(resultType指定實體類的全限定類名)