mybatis入门常见问题及解决方案详解

Mybatis 入门常见问题

Mybatis中文网

Mybatis中文链接:https://mybatis.net.cn/getting-started.html

其中涵盖 Mybatis 入门配置以及学习内容

Mybatis入门错误集合

错误一:时区问题

MySQL数据库的系统时区,其实是分两种的,一种是MySQL的全局时区,另外一种是当前会话的时区,如果当前会话不指定时区,就默认使用全局时区。

这里建议直接在环境配置的url中最后面加上 serverTimezone=GMTserverTimezone=Asia/Shanghai 如下:

<environment id="development">
    <transactionManager type="JDBC"/>
    <dataSource type="POOLED">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT"/>
        <property name="username" value="root"/>
        <property name="password" value="021001"/>
    </dataSource>
</environment>

或者在 idea 中的 Database 中设置:

<注: CST可视为美国、澳大利亚的标准时间>

错误二:字符编码问题(本人亲身经历,搞了一下午)

Error querying database.  Cause: java.sql.SQLException: Unsupported character encoding 'UFT-8'.

用户’root’@‘localhost’的访问被拒绝(使用密码:NO)原因:java.sql.SQLException:不支持字符编码’UFT-8’。

org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.sql.SQLException: Unsupported character encoding 'UFT-8'.
### The error may exist in com/hb/dao/UserMapper.xml
### The error may involve com.hb.dao.UserDao.getUserList
### The error occurred while executing a query
### Cause: java.sql.SQLException: Unsupported character encoding 'UFT8'.

	at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:156)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:147)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:142)
	at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:147)
	at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:80)
	at org.apache.ibatis.binding.MapperProxy$PlainMethodInvoker.invoke(MapperProxy.java:142)
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:86)
	at com.sun.proxy.$Proxy6.getUserList(Unknown Source)
	at com.hb.dao.UserDaoTest1.test(UserDaoTest1.java:17)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
	at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.sql.SQLException: Unsupported character encoding 'UFT8'.
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:861)
	at com.mysql.jdbc.ConnectionPropertiesImpl.postInitialization(ConnectionPropertiesImpl.java:2575)
	at com.mysql.jdbc.ConnectionPropertiesImpl.initializeProperties(ConnectionPropertiesImpl.java:2545)
	at com.mysql.jdbc.ConnectionImpl.initializeDriverProperties(ConnectionImpl.java:3143)
	at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:762)
	at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
	at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:386)
	at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
	at java.sql.DriverManager.getConnection(DriverManager.java:664)
	at java.sql.DriverManager.getConnection(DriverManager.java:208)
	at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.doGetConnection(UnpooledDataSource.java:228)
	at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.doGetConnection(UnpooledDataSource.java:223)
	at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.getConnection(UnpooledDataSource.java:96)
	at org.apache.ibatis.datasource.pooled.PooledDataSource.popConnection(PooledDataSource.java:452)
	at org.apache.ibatis.datasource.pooled.PooledDataSource.getConnection(PooledDataSource.java:100)
	at org.apache.ibatis.transaction.jdbc.JdbcTransaction.openConnection(JdbcTransaction.java:145)
	at org.apache.ibatis.transaction.jdbc.JdbcTransaction.getConnection(JdbcTransaction.java:67)
	at org.apache.ibatis.executor.BaseExecutor.getConnection(BaseExecutor.java:345)
	at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:89)
	at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:64)
	at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:333)
	at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:158)
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:110)
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:90)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:154)
	... 32 more

解决方案(需要排错,慢慢试):

  • 第一种情况:

可能是 url 中的characterEncoding写错了

<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="021001"/>
            </dataSource>
        </environment>
    </environments>

将mybatis-config配置中的 “url” 中的 value 中的 characterEncoding=UTF-8 中的 UTF-8 改成 UTF8 试试。

  • 第二种情况:

原因:这种情况可能是由于在创建表的时候没有设置编码格式,会默认成数据库的默认编码格式,即就是在一开始安装Mysql 时候创建文件 my.ini 的时候没有设置 default-character-set = utf8 导致的。

解决方案:

(一)、重新创建表,并设置编码格式,如下:

CREATE TABLE `user`(
	`id` INT(20) NOT NULL PRIMARY KEY,
	`name` VARCHAR(30) DEFAULT NULL,
	`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;

(二)、修改 mysql 配置文件

1、编辑MySql的配置文件

MySql 的配置文件在 Windows 下一般在MySql的安装目录下的 my.ini,Linux下一般是/etc/my.cnf

打开 my.ini 可以看到不同的标签下都会有 default-character-set后面 = 什么,如果此标签下已经存在 default-character-set=GBK一类的内容,只需将 ‘ = ’ 后面的内容修改为 utf8

如果标签下没有这一类的内容,则需要在 [mysqld] 、[mysql]、[client] 标签下加上一行

default-character-set = utf8

2、在命令行窗口处以管理员身份,重启 mysql 。

  • 输入 mysql -u root -p,紧接着输入自己的mysql密码;

    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 31
    Server version: 8.0.26 MySQL Community Server - GPL
    
    Copyright (c) 2000, 2021, Oracle and/or its affiliates.
    
    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.
    
    Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
    

    出现上述代码后,进行下面操作。

  • 输入查看数据库的编码方式的命令,即复制这个代码:show variables like 'character%';,回车,即可显示数据库编码格式,如下:

+--------------------------+--------------------------------------------------------+
| Variable_name            | Value                                                  |
+--------------------------+--------------------------------------------------------+
| character_set_client     | utf8mb3                                                |
| character_set_connection | utf8mb3                                                |
| character_set_database   | utf8mb3                                                |
| character_set_filesystem | binary                                                 |
| character_set_results    | utf8mb3                                                |
| character_set_server     | utf8mb3                                                |
| character_set_system     | utf8mb3                                                |
| character_sets_dir       | D:\HBApe\App\MySQL\mysql-8.0.26-winx64\share\charsets\ |
+--------------------------+--------------------------------------------------------+

如果修改成功,则重新运行,看是否会出现错误。

后续会出现的问题

1、修改数据库编码格式后查看,其格式没有发生变化:

可能修改完成后没有保存,或者没有重启mysql,这里建议重来一遍。

2、修改后无法启动 mysql:

可能是因为修改过程中,修改多了,或者增加了一些其他字符,重新检查一遍,再启动。

3、如果以上均不是的话,这里建议重新安装 MySQL,并重新配置(本人在这里犯错的时候,因为 mybatis 需要mysql的版本还有自己最早的配置等原因,最后也是重新安装了mysql,并重新进行了配置)。

错误三:Maven项目中配置文件无法生效问题

在最初使用Maven项目中,必然会遇到资源过略问题,Maven 由于它的约定大于配置,我们就会遇到在使用 Maven 项目过程中,XML文件或properties文件初始化失败,在生成目录中target中没有发现生成的XML文件或properties文件。

所以如何解决maven项目内资源过滤的问题,即写的配置文件无法被导出或者生效的问题?

解决方案:

在Maven项目中的 pom.xml 写 <build><build/> 标签,即:

<!--在build中配置resources,来防止我们资源导出失败的问题-->
  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
          <include>**/*.properties</include>
        </includes>
      </resource>

      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.xml</include>
          <include>**/*.properties</include>
        </includes>
      </resource>
    </resources>
  </build>

<注意:如果加了这个后还报错,建议重新启动 idea ,如果还有问题的话,那可能就是 idea 兼容问题了,建议降低版本重新下载>

希望上述整理可以帮到和我犯一样错误的有缘人,有错误的地方希望大佬指正!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HB0o0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值