mybatis基础操作问题总结

一、增加dependencies。两种情况:

    1.本地不存在相应jar包,此时通过在pom.xml文件中添加代码,由工具自动下载(sts为例)。

        如要添加mybatis,若本地不存在相关jar包,可搜索 mybatis mvn,选择版本,并将如下代码(图1)添加到pom.xml文件中(图2)


    2.本地存在相应jar包,则直接在pom.xml文件的dependencies选项卡中添加即可


总结:推荐第一次使用jar包时,通过工具自动下载,不然搞不清Maven Dependencies的目录结构

          未导入jar包时,工程目录中不会显示Maven Dependencies文件夹

二、核心配置文件configuration.xml

    可直接从mybatis官方文档中找到代码样例。地址:http://www.mybatis.org/mybatis-3/getting-started.html

    将Building SqlSessionFactory from XML中的代码全部复制到新建的configuration.xml文件中,并对driver、url以及mapper作出修改。此处需要注意到jdbc驱动包版本的问题。我使用的版本为8.0.11

<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/user?useSSL=false&amp;serverTimezone=UTC"/>
        <property name="username" value="root"/>
        <property name="password" value="521456"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="com/mybatis/dao/UserMapper.xml"/>
  </mappers>
</configuration>

错误总结:

    如果不在url后添加“serverTimezone=UTC”则在运行时会报错,

org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
### Cause: java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

    如果在url后面加入多个条件时,如还要加入useSSL=false条件 ,则中间不能只用“&”符号连接,因为xml文件中“&”字符是被禁止的,如要使用,则需要用转义字符“&amp;”,否则将会报错,

org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 97; 对实体 "serverTimezone" 的引用必须以 ';' 分隔符结尾。


猜你喜欢

转载自blog.csdn.net/chianing_han/article/details/80485504