MyBatis 连接数据库

Scroll Down

配置环境

创建maven项目

image.png

配置依赖项

pom.xml

  <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

从 XML 中构建 SqlSessionFactory

编写mybatis-config.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">
<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/数据库名"/>
                <property name="username" value="用户名"/>
                <property name="password" value="密码"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

创建连接类

public class MyConnector {
    private static SqlSessionFactory sqlSessionFactory;
    static{
        String resource = "mybatis-config.xml"; //数据库配置文件
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource); // 获取配置文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 生成SqlSessionFactory
    }
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession(); // 返回一个SqlSession
    }
}