mybatis-1-hellomybatis

流程:

创建一个mybatis的数据表

USE `mybatis`;

CREATE TABLE tbl_employee(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
last_name VARCHAR(255),
gender CHAR(1),
email VARCHAR(255)
)

再添加数据

image-20210416164829689

导入依赖

<dependencies>
    <!--mybatis的依赖-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <!-- mysql驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>
    <!--junit测试板块-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <!--lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.16</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

<!--让java文件夹中的.xml也能被编译-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

创建实体类

package com.wang.mybatis;

public class Employee {
    private Integer id;
    //注意:这里的lastname和数据库中的last_name是不一样的
    private String lastName;
    private String email;
    private String gender;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }


    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", gender='" + gender + '\'' +
                '}';
    }
}

创建主配置文件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>
    <!--配置MyBatis运行环境-->
    <environments default="development">
        <environment id="development">
            <!--配置JDBC的事务管理-->
            <transactionManager type="JDBC"/>
            <!--POOLED配置JDBC数据源连接池-->
            <dataSource type="POOLED">
                <!--如下, 如果不指定编码, 可能会报空指针异常-->
                <!-- <property name="url" value="jdbc:mysql://localhost:3306/ryan?serverTimezone=GMT%2B8"/> -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!--注册EmployeeMapper.xml-->
    <mappers>
        <mapper resource="com/wang/dao/xml/EmployeeMapper.xml"/>
    </mappers>
</configuration>

创建dao包,其下创建EmployeeMapper接口

public interface EmployeeMapper {
    Employee selectEmployee(int id);

    List<Employee> getAllEmployee();
}

在dao包下创建xml文件夹,在下面创建EmployeeMapper.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的值为mapper对应的那个类的包名-->
<mapper namespace="com.wang.dao.EmployeeMapper">
    <resultMap id="employeeMap" type="com.wang.entity.Employee">
        <id column="id" property="id"/>
        <result column="last_name" property="lastName"/>
        <result column="email" property="email"/>
        <result column="gender" property="gender"/>
    </resultMap>
    <!--resultType的值为对应的Java类-->
    <!--id可以理解为唯一标识,之后将通过id调用对应sql-->
    <select id="selectEmployee" resultMap="employeeMap">
        <!--#{id}类似于jdbc中的占位符?,表示传过来的参数-->
        select id,last_name,gender,email from tbl_employee where id = #{id}
    </select>

    <!--List<Employee> getAllEmployee();-->
    <select id="getAllEmployee" resultMap="employeeMap">
        select id,last_name,gender,email from tbl_employee
    </select>
</mapper>

将mapper配置文件加载到mybais的配置文件 mybatis-config.xml 中:

...

<!--注册EmployeeMapper.xml-->
<mappers>
    <mapper resource="com/wang/dao/xml/EmployeeMapper.xml"/>
</mappers>
...

创建Test类, 在这里操作数据库数据:

@org.junit.Test
    public void test1(){
    InputStream resourceAsStream = Test.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();

    EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
    List<Employee> allEmployee = mapper.getAllEmployee();
    System.out.println(allEmployee);
    sqlSession.close();
}

使用Druid数据源

流程:

加入依赖:

<!--Druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.8</version>
</dependency>

成品:

<dependencies>
    <!--mybatis的依赖-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <!-- mysql驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>
    <!--Druid-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.8</version>
    </dependency>
    <!--junit测试板块-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <!--lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.16</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

<!--让java文件夹中的.xml也能被编译-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

写Druid的配置类

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.datasource.DataSourceFactory;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

public class DruidConfig implements DataSourceFactory {

    private Properties properties;

    //把properties配置文件导入到这里来
    @Override
    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @Override
    public DataSource getDataSource() {
        DruidDataSource dds = new DruidDataSource();
        dds.setUrl(this.properties.getProperty("url"));
        dds.setUsername(this.properties.getProperty("username"));
        dds.setPassword(this.properties.getProperty("password"));
        try {
            dds.init();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dds;
    }
}

在mybatis-config.xml中修改数据源配置

之前:

<dataSource type="POOLED">
    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8"/>
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
</dataSource>

之后:

<!-- 外部 properties 配置文件  -->
<properties resource="db.properties"/>

...
<!-- type属性修改成我们刚刚写好的配置类  -->
<dataSource type="com.wang.config.DruidConfig">
    <property name="driver" value="${jdbc.driverClass}"/>
    <property name="url" value="${jdbc.jdbcUrl}"/>
    <property name="username" value="${jdbc.user}"/>
    <property name="password" value="${jdbc.password}"/>
</dataSource>

这里是把数据源配置单独拎出来了

创建一个db.properties

jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8
jdbc.user=root
jdbc.password=123456
posted @ 2021-06-07 16:00  Coder-Wang  阅读(42)  评论(0编辑  收藏  举报