mybatis连接mysql数据库

mybatis连接mysql数据库

1.创建一个空的maven项目

mybatis连接mysql数据库

2.在项目的pom.xml文件中导入所需要的依赖,依赖如下:

没有配置镜像的会导入较慢

<dependencies>

    <!--数据库驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.9</version>
    </dependency>

    <!--mybatis-->
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.5</version>
    </dependency>

    <!--单元测试-->
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>
</dependencies>

此外还需要导入过滤文件的xml代码,如下:

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

<!--设置字符集-->
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

自动导入之后看这里有没有依赖包,没有的话就说明没导入成功:

mybatis连接mysql数据库

3、创建数据库表

mysql创建数据库表语句:

CREATE TABLE users(
ID INT(10) NOT NULL AUTO_INCREMENT COMMENT ‘用户id‘,
Name VARCHAR(100) NOT NULL COMMENT ‘用户名‘,
Age INT(11) NOT NULL COMMENT ‘年龄‘,
KEY ID (ID)
)ENGINE=INNODB DEFAULT CHARSET=utf8

添加数据语句:

INSERT INTO users (ID,Name,AGE) VALUES
(1,‘小明‘,10),
(2,‘小蓝‘,3),
(3,‘小黄‘,4),
(4,‘小绿‘,2);

数据库表:

mybatis连接mysql数据库

4、实体类

public class User {
    //字段名与数据库保持一致
    private int ID;
    private String Name;
    private int Age;
    
    //有参和无参构造方法
    public User(int ID, String name, int age) {
        this.ID = ID;
        Name = name;
        Age = age;
    }
    public User() {
    }

    //get and set 方法
    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public int getAge() {
        return Age;
    }

    public void setAge(int age) {
        Age = age;
    }
    
    
    //toString方法
    @Override
    public String toString() {
        return "User{" +
                "ID=" + ID +
                ", Name=‘" + Name + ‘\‘‘ +
                ", Age=" + Age +
                ‘}‘;
    }
}

5、dao层的UserDao接口方法和Mapper配置文件

dao层的接口:

package com.ma.dao;

import com.ma.pojo.User;

import java.util.List;

public interface UserDao {
    List<User> getList();
}

dao层的配置文件:

配置文件可以去官网查找:https://mybatis.org/mybatis-3/zh/index.html

<?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="com.ma.dao.UserDao">
    <select id="getList" resultType="com.ma.pojo.User">
       select * from users
   </select>
</mapper>

注意:配置文件与接口要在同一个包下,否则配置文件扫描接口时无法扫描接口的方法

6、mybatis的配置文件

在resources资源包下创建一个mybatis-config.xml的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>
    <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/text?useSSL=true&amp;userUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/ma/dao/UserMapper.xml"/>
    </mappers>
</configuration>

7、mybatis的java工具类

创建一个工具类的包,在工具类的包中创建一个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;

public class MybatisUtil {
    private static SqlSessionFactory 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();
        }
    }

    //获取SqlSessiond对象
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}

8、测试

public class MyTest {
    @Test
    public void Test1(){
        //第一步:获取sqlSession对象
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        //第二步:执行sql
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        //第三步:执行方法
        List<User> userList = mapper.getList();
        //第四步:循环打印
        for (User user : userList) {
            System.out.println(user);
        }
        //第五步:关闭sqlSession
        sqlSession.close();
    }
}

9、结果

mybatis连接mysql数据库

10、结构

mybatis连接mysql数据库

11、几个常用的网址

1、maven仓库:https://mvnrepository.com

2、spring官方文档:https://docs.spring.io/spring/docs/5.2.7.RELEASE/spring-framework-reference/core.html

3、mybatis官网:https://mybatis.org/mybatis-3/zh/index.html

mybatis连接mysql数据库

上一篇:Mysql一些管理类的指令


下一篇:MySQL创样例表(MySQL必知必会B.2)