zoukankan      html  css  js  c++  java
  • mybatis入门案例测试常见问题以及解决方法

    1、什么是Mybatis

    在这里插入图片描述

    • MyBatis 是一款优秀的持久层框架
    • 它支持定制化 SQL、存储过程以及高级映射。
    • MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
    • MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
    • MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。
    • 2013年11月迁移到Github。

    注:如果你想了解mybatis更多历史信息,建议百度百科https://baike.baidu.com/item/MyBatis/2824918?fr=aladdin

    2、如何获得Mybatis?

    github
    https://github.com/mybatis/mybatis-3
    在这里插入图片描述
    在这里插入图片描述
    Github : https://github.com/mybatis/mybatis-3/releases

    中文文档:https://mybatis.org/mybatis-3/zh/index.html

    3、pom.xml的jar包从哪里获取?

    maven远程仓库https://mvnrepository.com/

     <!--导入依赖-->
        <dependencies>
            <!--mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
            <!--mybatis-->
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.2</version>
            </dependency>
            <!--junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/log4j/log4j -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
    
        </dependencies>
    

    建议:选择使用人数最多的版本

    4、为什么需要Mybatis?

    • 帮助程序猿将数据存入到数据库中。
    • 方便
    • 传统的JDBC代码太复杂了。简化。框架。自动化。
    • 不用Mybatis也可以。更容易上手。 技术没有高低之分
    • 优点:
      • 简单易学
      • 灵活
      • sql和代码的分离,提高了可维护性。
      • 提供映射标签,支持对象与数据库的orm字段关系映射
      • 提供对象关系映射标签,支持对象关系组建维护
      • 提供xml标签,支持编写动态sql。

    最重要的一点:使用的人多!

    Spring SpringMVC SpringBoot

    5、mybatis环境如何搭建?

    环境搭建

    1. 创建maven工程,导入坐标

    2. 创建实体类和dao接口

    3. 创建主配置文件

      SqlMapConfig.xml

    <?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">
    <!--以上是config的约束-->
    <!--编写mybatis的主配置文件-->
    <configuration>
    <!--    配置环境-->
        <environments default="mysql">
    <!--        配置mysql环境-->
            <environment id="mysql">
    <!--            配置事务的类型-->
                <transactionManager type="JDBC"/>
    <!--            配置数据源(连接池)            -->
                <dataSource type="POOLED">
    <!--                配置连接数据库的4个基本信息-->
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/数据库名?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="用户密码"/>
                </dataSource>
            </environment>
        </environments>
    
    <!--    指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
        <mappers>
            <mapper resource="com/wan/dao/IUserDao.xml"/>
        </mappers>
    </configuration>
    
    1. 创建映射配置文件

      IUserDao.xml

    <?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=绑定一个对应的Dao/Mapper接口-->
    <mapper namespace="com.wan.dao.IUserDao">
    <!--    配置查询所有-->
       <!-- is是IUserDao里的方法名
       //    查询所有操作
        List<User> findAll();-->
    <select id="findAll" resultType="com.wan.mybatis.User">
        select *from user;
    </select>
    </mapper>
    

    6、不支持发行版本X

    第一步:检查maven配置

    在这里插入图片描述
    第二步:检查java版本是否一致

    在这里插入图片描述
    第三步:检查项目结构

    在这里插入图片描述
    在这里插入图片描述

    7、日志发出警告

    log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
    log4j:WARN Please initialize the log4j system properly.
    log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
    

    解决方法一:

    新建配置文件:log4j.properties
    在这里插入图片描述

    log4j.rootLogger=debug, stdout, R
    
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    
    # Pattern to output the caller's file name and line number.
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
    
    log4j.appender.R=org.apache.log4j.RollingFileAppender
    log4j.appender.R.File=example.log
    
    log4j.appender.R.MaxFileSize=100KB
    # Keep one backup file
    log4j.appender.R.MaxBackupIndex=5
    
    log4j.appender.R.layout=org.apache.log4j.PatternLayout
    log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
    
    
    

    实际上,还是推荐把这个文件夹放在src/main/resources下。

    如果继续报错或者警告

    解决方法二:手动建立工具包存放工具类

    
    
    import org.apache.log4j.PropertyConfigurator;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Properties;
    
    public class initLogRecord {
        public static void initLog() {
            FileInputStream fileInputStream = null;
            try {
                Properties properties = new Properties();
                fileInputStream = new FileInputStream("src/main/resources/log4j.properties");
                properties.load(fileInputStream);
                PropertyConfigurator.configure(properties);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    

    实际上,最重要的就是

    fileInputStream = new FileInputStream("src/main/resources/log4j.properties");
    

    根据自己的需要指定这个配置文件的路径。

    8、配置文件出错

    我的配置文件:SqlMapConfig.xml

    错误内容:

    org.apache.ibatis.exceptions.PersistenceException:
    Error building SqlSession.
    Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 4; columnNumber: 16; 必须声明元素类型 "configuration"。
    

    解决方法:修改config约束头

    <?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">
    
    <?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">
    

    9、maven资源导出问题

    maven由于他的约定大于配置,我们之后可以能遇到我们写的配置文件,无法被导出或者生效的问题

    解决方案:

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

    我的CSDN主页链接:https://blog.csdn.net/weixin_46047285

    10、mybatis项目01IDEA界面总览图

    在这里插入图片描述

    11、数据库数据表附件

    -- 创建数据库
    create database if not exists db_mybatis character set utf8;
    -- 创建数据表
    drop table if exists `user`;
    create table `user` (
      `id` int(11) not null auto_increment,
      `username` varchar(32) not null comment '用户名称',
      `birthday` datetime default null comment '生日',
      `sex` char(1) default null comment '性别',
      `address` varchar(256) default null comment '地址',
      primary key  (`id`)
    ) engine=innodb default charset=utf8;
    -- 添加记录
    insert  into `user`(`id`,`username`,`birthday`,`sex`,`address`) 
    values (17,'wan1','2000-02-27 17:47:08','男','湖北武汉'),
    (18,'wan2','2000-03-02 15:09:37','女','云南昆明'),
    (19,'wan3','2001-03-04 11:34:34','女','广西贵港'),
    (20,'wan4','2002-03-04 12:04:06','男','湖北恩施'),
    (21,'wan5','1999-03-07 17:37:26','男','云南文山'),
    (22,'wan6','1998-03-08 11:44:00','女','湖南长沙');
    
  • 相关阅读:
    尤瓦尔•赫拉利简史三部曲读书笔记
    5星|《城市与国家财富》:经济发展的基本单位是城市而不是国家
    oracle SQL Develop导出数据库中的表格数据到excel
    selvert的过滤器filter处理中文乱码
    jsp中四种传递参数的方法
    Mybatis中配置Mapper的方法
    JAVA文件中获取路径及WEB应用程序获取路径方法
    MyEclipse 常用设置
    Java连接oracle数据库的OCI和thin
    Java连接oracle数据库的OCI和THIN
  • 原文地址:https://www.cnblogs.com/wanwanyuan/p/13512802.html
Copyright © 2011-2022 走看看