第一个MyBatis程序

思路:搭建环境——>导入依赖的jar包——>编写代码——>测试

1、搭建环境

  1. 搭建数据库

    CREATE DATABASE `mybatis`;
    
    USE `mybatis`;
    
    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;
    
    INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
    (1,'狂神','166985'),
    (2,'张三','869665'),
    (3,'李四','899966')
    
  2. 新建一个普通的maven项目,删除src目录,以后以这个项目为父工程;

  3. 导入依赖的jar包;

    <!--依赖的jar包-->
        <dependencies>
            <!--连接数据库 https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.20</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.6</version>
            </dependency>
            <dependency>
                <!--测试依赖的jar-->
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    

2、创建一个普通的maven模块

  1. 编写MyBatis的核心配置文件;

    <?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:mybatis核心配置文件-->
    <configuration>
        <!--environments:环境-->
        <environments default="development">
            <environment id="development">
                <!--transactionManager:事务-->
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&amp;useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>
    </configuration>
    
  2. 编写MyBatis工具类

    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;
    
    //获取SqlSessionFactory,工具类
    public class MyBatisUtil {
        private static SqlSessionFactory sqlSessionFactory;
    
        static {
            //使用MyBatis获取SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = null;
            try {
                inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //现在有了SqlSessionFactory,您可以获取SqlSession的实例。SqlSession绝对包含对数据库执行SQL命令所需的所有方法。
        // 您可以直接对SqlSession实例执行映射的SQL语句。
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    }
    

3、编写代码

  1. 实体类;

    package com.beyond.pojo;
    
    //实体类
    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. Dao接口;

    import com.beyond.pojo.User;
    
    import java.util.List;
    
    public interface UserDao {
        List<User> getUserList();
    }
    
  3. 接口实现类(由原来的UserDaoImpl转变为一个Mapper.xml配置文件);

    注意:最好是将上面的Dao接口的接口名与Mapper.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.beyond.dao.UserDao">
        <!--查询语句:
        id:对应namespace中的方法名;
        resultType:sql语句执行的返回值;
        parameterType:参数类型
        -->
        <select id="getUserList" resultType="com.beyond.pojo.User">
        select * from mybatis.user
        </select>
    </mapper>
    

4、junit测试

import com.beyond.pojo.User;
import com.beyond.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {
    @Test
    public void test(){
        //1、获得SqlSession对象
        SqlSession sqlSession= MyBatisUtil.getSqlSession();
        //2、执行SQL
        //方式一:getMapper
        UserDao userDao=sqlSession.getMapper(UserDao.class);
        List<User> userList= userDao.getUserList();
        for (User user:userList) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
    }
}

注意报错:

org.apache.ibatis.binding.BindingException: Type interface com.beyond.dao.UserDao is not known to the MapperRegistry.

解决方法:

<!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册-->
    <mappers>
        <mapper resource="com.beyond.dao.UserMapper.xml"/>
    </mappers>
//然后又会报一个错误
Caused by: java.io.IOException: Could not find resource com/beyond/dao/UserMapper.xml

这是因为maven由于它的约定大于配置,我们之后可能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案:

<!--在build中配置resources,来防止我们资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
已标记关键词 清除标记
相关推荐
<p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;">本课程以通俗易懂的方式讲解MyBatis技术,课程内容包括:</span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;">1. MyBatis简介</span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;">2. 第一个MyBatis程序</span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;">3. 基于接口的实现</span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;">4. MyBatisUtil工具类</span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;">5. CRUD操作</span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;">6. 手动映射</span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;">7.多参数查询</span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;">8.动态SQL</span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;">9.多表关系映射</span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;">10.代码生成器mybatis-generator</span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;">11.分页插件PageHelper</span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;"><br /> </span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;"><strong><span style="color:#FF0000;">教学全程采用笔记+代码案例的形式讲解,通俗易懂!!!</span></strong><br /> </span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;"><br /> </span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;"><img src="https://img-bss.csdn.net/201906230153532330.png" alt="" /><br /> </span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;"><br /> </span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;"><img src="https://img-bss.csdn.net/201906230154045006.png" alt="" /><br /> </span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;"><br /> </span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;"><img src="https://img-bss.csdn.net/201906230154145759.png" alt="" /><br /> </span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;"><br /> </span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;"><img src="https://img-bss.csdn.net/201906230154247034.png" alt="" /><br /> </span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;"><br /> </span> </p> <p style="color:#424242;font-size:14px;background-color:#FFFFFF;"> <span style="font-size:16px;"><img src="https://img-bss.csdn.net/201906230154347084.png" alt="" /><br /> </span> </p>
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页