狂神说 第一个mybatis程序步骤及问题解决

mybatisplus开始学习时,常出现的错误 mybatisplus开始学习时,常出现的错误。错误已解决 有整个测试详细详细源码 阅读详情

mybatis中文文档网址:MyBatis中文网

1.创建数据库

1.创建一个USER表

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;

2.插入数据

INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,"张三","123456"),
(2,"李四","1234567"),
(3,"王五","12345689");

2.创建maven项目

 

 

 看自己的maven是不是idea自带的,如果是的话,修改成自己安装的。

 

 

2.2、导入项目需要的包

MySQL的版本一定要和自己的版本一致,否则就会报错,下面的问题中有个错误就是因为版本不对导致的。

<!--导包-->
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

2.3、重新创建一个maven项目

2.4、在resources中创建mybatis-config的配置文件mybatis-config.xml

MySQL 5.1版本的

<?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">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306?                      useSSL=true&amp;useUnicode=true&amp;charactorEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>

MySQL5.8版本的

<?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">
<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;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/fan/dao/UserMapper.xml"/>
    </mappers>
</configuration>

2.5、编写mybatis工具类MybatisUtil

package com.fan.utils;
​
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
​
import java.io.IOException;
import java.io.InputStream;
​
public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            //使用mybatis的第一步:获取SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}
 

2.6、编写实体类

快捷键 alt+insert

package com.fan.entity;
​
public class User {
    private int id;
    private String name;
    private String pwd;
​
    public User() {
    }
​
    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }
​
    public int getId() {
        return id;
    }
​
    public void setId(int id) {
        this.id = id;
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public String getPwd() {
        return pwd;
    }
​
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
​
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

2.7、创建Dao接口

package com.fan.dao;
​
import com.fan.entity.User;
​
import java.util.List;
​
public interface UserDao {
    List<User> getUserList();
}

2.8、编写接口实现类UserMapper.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">
<!--namespace=绑定一个Dao/Mapper接口-->
<mapper namespace="com.fan.dao.UserDao">
    <select id="getUserList" resultType="com.fan.entity.User">
    select * from mybatis.user;
  </select>
</mapper>

3.测试

在test文件夹中创建与src下的main中相同的结构(推荐),快捷键:在UserDao接口的代码块内按住alt+insert

测试代码如下:
 

package com.fan.dao;

import com.fan.entity.User;
import com.fan.utils.MybatisUtil;
import junit.framework.TestCase;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest extends TestCase {
    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        //关闭
        sqlSession.close();
    }
}

注意:记得关闭sqlSession

修改mybatis-config.xml中的mappers

<mappers>
        <mapper resource="com/fan/dao/UserMapper.xml"/>
</mappers>

 修改之后就可以运行代码了。

4.解决运行时错误

4.1、问题1

java.lang.ExceptionInInitializerError
    at com.fan.dao.UserDaoTest.test(UserDaoTest.java:14)
    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 junit.framework.TestCase.runTest(TestCase.java:176)
    at junit.framework.TestCase.runBare(TestCase.java:141)
    at junit.framework.TestResult$1.protect(TestResult.java:122)
    at junit.framework.TestResult.runProtected(TestResult.java:142)
    at junit.framework.TestResult.run(TestResult.java:125)
    at junit.framework.TestCase.run(TestCase.java:129)
    at junit.framework.TestSuite.runTest(TestSuite.java:252)
    at junit.framework.TestSuite.run(TestSuite.java:247)
    at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### The error may exist in com/fan/dao/UserMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/fan/dao/UserMapper.xml
    at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
    at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80)
    at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64)
    at com.fan.utils.MybatisUtil.<clinit>(MybatisUtil.java:18)
    ... 19 more
Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/fan/dao/UserMapper.xml
    at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:122)
    at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:99)
    at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:78)
    ... 21 more
Caused by: java.io.IOException: Could not find resource com/fan/dao/UserMapper.xml
    at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:114)
    at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:100)
    at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:374)
    at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:120)
    ... 23 more
​
​
Process finished with exit code -1
 

解决方法:在pom.xml文件中添加如下代码:

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

4.2、问题2

org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.sql.SQLException: Error setting driver on UnpooledDataSource. Cause: java.lang.ClassNotFoundException: Cannot find class: com.mysql.cj.jdbc.Driver
### The error may exist in com/fan/dao/UserMapper.xml
### The error may involve com.fan.dao.UserDao.getUserList
### The error occurred while executing a query
### Cause: java.sql.SQLException: Error setting driver on UnpooledDataSource. Cause: java.lang.ClassNotFoundException: Cannot find class: com.mysql.cj.jdbc.Driver

解决方法:

我的MySQL是8.0版本的,而我的pom.xml文件中导入的包是5.1版本的,所以需要把版本换成8.0版本的就好了。

4.3、问题3

 这里没有勾选也有可能出错。

在SSM(Spring + SpringMVC + MyBatis)框架中,org.apache.ibatis.session.SqlSessionMyBatis框架中的一个核心接口 在SSM框架中,你可以通过Spring的依赖注入(@Autowired)来注入Mapper接口的实例,并在Service层中调用Mapper接口的方法来执行数据库操作。这样,你就可以在Service层中专注于业务逻辑的实现,而无需关心底层的数据库操作细节。在SSM(Spring + SpringMVC + MyBatis)框架中,org.apache.ibatis.session.SqlSessionMyBatis框架中的一个核心接口,它表示和数据库的一次会话,用于执行CRUD(增删改查)操作。 阅读详情

相关推荐

SpringBoot 笔记

Java SpringBoot SpringBoot01:Hello,World! SpringBoot02:运行原理初探 SpringBoot03:yaml配置注入 SpringBoot04:JSR303数据校验及多环境切换 SpringBoot05:自动配置原理 SpringBoot06:自定义starter SpringBoot07:整合JDBC SpringBoot08:整合Druid SpringBoot09:整合MyBatis S

DDDDeng_的博客 3万+

org.apache.ibatis.binding.BindingException: Type interface com.dao.UserMapper is not known to the Ma

org.apache.ibatis.binding.BindingException: Type interface com.dao.UserMapper is not known to the MapperRegistry. at org.apache.ibatis.binding.MapperRegistry.getMapper(MapperRegistry.java:47) at org.apache.ibatis.session.Configuration.getMapper(Configu.

qq_45689209的博客 1262

Mybatis视频学习详细笔记

基础知识: JDBC Mysql Java基础 Maven Junit 框架:是有配置文件的。最好的方式:看官网文档 1、简介 1.1、什么是MyBatis 简介 什么是 MyBatisMyBatis 是一款优秀的持久层框架 它支持定制化 SQL、存储过程以及高级映射。 MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。 MyBatis 可以使用简单的 XML 或...

xiangminlu的博客 5300

Mybatis基础版本1.0

Mybatis 环境:JDK,Mysql,maven,idea https://blog.csdn.net/qq_40253426/article/details/108986838 1、简介 1.1、什么是Mybaits? Mybaits是一款==持久层框架== 它支持自定义 SQL、存储过程以及高级映射。 MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。 MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Ol

weixin_45467873的博客 834

sqlSessionFactory空指针问题

sqlSessionFactory空指针问题java.lang.NullPointerException: Cannot invoke "org.apache.ibatis.session.SqlSessionFactory.openSession()" because "com.test.utils.MybatisUtils.sqlSessionFactory" is null错误的情况正确的情况因此,当出现问题,找了各个办法还没找到原因时,可以看看target文件夹中是否有对应需要测试的文件存在 jav

Darth_Devil的博客 6075

MyBatis01:第一个程序

MyBatis系列连载课程,通俗易懂,基于MyBatis3.5.2版本,欢迎各位粉转发关注学习,视频同步文档。未经作者授权,禁止转载MyBatis简介环境明:jdk 8 +My...

狂神说 1万+

SpringMVC05:整合SSM框架

SpringMVC系列连载课程,通俗易懂,基于Spring5版本(视频同步),欢迎各位粉转发关注学习。未经作者授权,禁止转载整合SSM框架在上一节中,我们了解了SpringMVC...

狂神说 4万+

终于,SSM及SpringBoot系列文章完更!!!

经过了近一个月的时间,小终于将SSM及SpringBoot视频对应文章更新完毕!!!记得文末喜欢走一波,码字不易,从公众号开通,就保持日更,何尝不是一种打卡呢?你们都坚持看了吗~如果...

狂神说 25万+

MyBatis06:动态SQL

MyBatis系列连载课程,通俗易懂,基于MyBatis3.5.2版本,欢迎各位粉转发关注学习,视频同步文档。未经作者授权,禁止转载动态SQL介绍什么是动态SQL:动态SQL指的...

狂神说 5139

Java Mybatis笔记

MyBatis 1、简介 1.1 什么是Mybatis MyBatis 是一款优秀的持久层框架; 它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。 1.2 持久化 数据持久化 持久化就是将程序的数据在持久状态和瞬时状态转化的过程 内存:断电即

DDDDeng_的博客 4万+

Mybatis学习笔记(全)

Mybatis 环境 JDK1.8 Mysql5.7 maven 3.6.1 IDEA 回顾 JDBC Mysql Java基础 Maven Junit SSM框架:配置文件的最好的方式:看官网文档 Mybatis 1、Mybatis简介 1.1 什么是Mybatis 如何获得Mybatis maven仓库: 中文文档:https://mybatis.org/mybatis-3/zh/index.html Github: 1.2 持久化 数据持久化 持久化就是将程序的数据在持久状态和瞬时状态转

li643937579的博客 4万+

Java Mybatis的详细笔记(完整版)

最近在B站找教程视频自学java框架(SSM),最后发现自己迷上了,不得不秦疆老师 讲得太好了,通俗易懂,而且在听他的课你会不由衷得到一些思想的启发和转变,而且教程视频 还是无偿免费的,还有课程笔记源码,好东西废话不多,搬运过来整理分享给大家,共同成长! MyBatis 1、简介 1.1 什么是Mybatis MyBatis 是一款优秀的持久层框架; 它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis

weixin_44822455的博客 1万+

Spring08:整合MyBatis

Spring系列连载课程,通俗易懂,基于Spring最新版本,欢迎各位粉转发关注学习。禁止随意转载,转载记住贴出B站视频链接及公众号链接!整合MyBatis步骤1、导入相关jar...

狂神说 1万+

Mybatis笔记

. 资料来源 mybatis B站视频链接 b站视频链接,点击跳转 Mybatis的官网 二. 大概分了如下模块: Mybatis01:第一个程序 Mybatis02:CRUD操作及配置解析 Mybatis03:ResultMap及分页 Mybatis04:只用注解开发 Mybatis05:一对多和多对一处理 Mybatis06:动态SQL Mybatis07:缓存 三.正式开始学习 (一)Mybatis第一个程序 环境搭建 jdk 8 + MySQL 5.

热爱编写程序的药学在读书 548

MyBatis03:ResultMap及分页

MyBatis系列连载课程,通俗易懂,基于MyBatis3.5.2版本,欢迎各位粉转发关注学习,视频同步文档。未经作者授权,禁止转载ResultMap上集回顾:MyBati...

狂神说 6217

SSM框架:SpringMVC + Spring + MyBatis(详细笔记完整版)

最近在B站找教程视频自学java框架(SSM),最后发现自己迷上了,不得不秦疆老师 讲得太好了,通俗易懂,而且在听他的课你会不由衷得到一些思想的启发和转变,而且教程视频 还是无偿免费的,还有课程笔记源码,好东西废话不多,搬运过来整理分享给大家,共同成长! spring 的详细笔记(完整版) springmvc 的详细笔记(完整版) Java Mybatis的详细笔记(完整版) ...

weixin_44822455的博客 9006

MyBatis07:缓存

MyBatis系列连载课程,通俗易懂,基于MyBatis3.5.2版本,欢迎各位粉转发关注学习,视频同步文档。未经作者授权,禁止转载缓存简介1、什么是缓存 [ Cache ]?存...

狂神说 4020
上一篇: MarkDown语法
下一篇: 第一个Spring项目无法创建Cannot download ‘https://start.spring.io‘: connect timed out
饭好香学Java
博客等级 码龄5年 0粉丝 6原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值