EchoDemo's Blogs

mybatis学习中碰到的的一些问题

君不见走马川行雪海边,平沙莽莽黄入天。

轮台九月风夜吼,一川碎石大如斗,随风满地石乱走。

匈奴草黄马正肥,金山西见烟尘飞,汉家大将西出师。

将军金甲夜不脱,半夜军行戈相拨,风头如刀面如割。

马毛带雪汗气蒸,五花连钱旋作冰,幕中草檄砚水凝。

虏骑闻之应胆慑,料知短兵不敢接,车师西门伫献捷。

—-唐·岑参《走马川行奉送封大夫出师西征》

1、元素类型为 "configuration" 的内容必须匹配 "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,plugins?,environments?,databaseIdProvider?,mappers?)"。

org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 46; columnNumber: 17; 元素类型为 "configuration" 的内容必须匹配 "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)"。

mybatis-config.xml配置文件配置时,要注意节点顺序。


2、<property name="username" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf-8" />

org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the connection string near ';serverTimezone=UTC'.

这是时区问题,只需配置成下面这样就OK了(其中的&表示的是XML的&字符的转义符,所以当你在把这个配置放到db.properties中时就要将&改回&字符了,不然也会报错):

<property name="username" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf-8&amp;serverTimezone=UTC" />

3、org.apache.ibatis.binding.BindingException: Type interface com.echodemo.mybatislearning.mapper.UserMapper is not known to the MapperRegistry

这个是因为xml文件没有被添加到mybatis的配置文件中扫描。在这里我的mapper当时是这样配置的,看到网上很多都是在前面加个mapper就OK了,but我的目录结构估计和他们不一样。那么如何优雅让工程找到我们的映射文件呢?

<!--我的-->
<mappers>
    <mapper resource="UserMapper.xml"></mapper>
</mappers>

<!--网上众多博客-->
<mappers>
    <mapper resource="mapper/UserMapper.xml"></mapper>
</mappers>

我在pom文件的bulid里面添加了下面这个路径的指引,再也不怕找不到我的映射文件了,哈哈。

<resources>
    <resource>
        <directory>src/main/java/com/echodemo/mybatislearning/mapper</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
</resources>

当然如果说你是想要配置成批量加载的话,可以像下面这样:

<mappers>
    <!-- 批量加载mapper
    指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载
    遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,
    且在一个目录中上边规范的前提是:使用的是mapper代理方法
     -->
    <package name="com.echodemo.mybatislearning.mapper"/>
</mappers>

<!--还是要在pom文件当中定义路径哈!-->
<resource>
    <directory>src/main/java</directory>
    <includes>
        <include>**/*.xml</include>
    </includes>
</resource>

4、IDEA中使用Mybatis的逆向工程提示说找不到配置文件generatorConfig.xml的问题

网上很多的文章和博客在指定逆向工程配置文件的时候都是直接用的”generatorConfig.xml”的文件名,而没有前面的路径,虽然按住ctrl可以跳转到该文件,但是在运行main方法的时候却总是报”未找到该文件”的错。我是这样配置的就可以了:

//指定逆向工程配置文件
File configFile = new File("src\\main\\resources\\generatorConfig.xml");
🐶 您的支持将鼓励我继续创作 🐶
-------------本文结束感谢您的阅读-------------