09 myBatis-01

介紹項目中如何使用myBais完成數據庫的訪問

0、項目文件結構

1、pom.xml配置

引入myBatis包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.rui</groupId>
    <artifactId>01QuickStart</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.3.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.3.0</version>
        </dependency>

        <!--jdbcTemplate-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.0</version>
        </dependency>

        <!--MySQL連接的依賴包-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <!-- https://mybatis.org/mybatis-3/getting-started.html -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>

        <!--單元測試-->
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <!--日誌輸出-->
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>

</project>

2、Mybatis主配置文件

在main/Resources跟目錄下創建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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://47.100.229.xxx:3306/springStudy?useSSL=false&serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="xxx"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 引入表的Mapper文件 -->
    <mappers>
        <mapper resource="db/mapper/EmployeeMapper.xml"/>
    </mappers>
</configuration>

3、單個表對應的內容

3.1、模型類

根據表接口定義模型類,屬性名和字段名保持統一

package db.Domain;

import org.springframework.stereotype.Component;

import java.sql.Date;

@Component(value = "employee")
public class Employee {
    private String emplId;
    private String name;
    private String gender;
    private Date hireDate;
    private int salary;

    public String getEmplId() {
        return emplId;
    }
    public void setEmplId(String emplId) {
        this.emplId = emplId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public Date getHireDate() {
        return hireDate;
    }
    public void setHireDate(Date hireDate) {
        this.hireDate = hireDate;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "emplId='" + emplId + '\'' +
                ", name='" + name + '\'' +
                ", gender=" + gender +
                ", hireDate=" + hireDate +
                ", salary=" + salary +
                '}';
    }
}

3.2、數據接口類

根據業務需求定義所需要的相關數據操作方法

package db.Dao;

import db.Domain.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;

//數據訪問接口
public interface EmployeeDao {

    //查詢單個對象,單個參數時@Param可以省略
    public Employee queryByEmplId(@Param("emplId") String empId);

    //查詢多個對象,多個參數時需要通過@Param聲明
    public List<Employee> queryListBySalary(@Param("start") int start,@Param("end") int end);

    //新增數據
    public int insert(Employee emp);

    //更新數據
    public int update(Employee emp);

    //刪除數據
    public void delete(@Param("emplId") String empId);
}

3.3、Mapper文件

文件保存在main/Resources/db/Mapper/目錄內

右擊:Resource選擇創建目錄,輸入“db/Mapper”即可。

根據接口類內部的方法定義Mapper內的相關操作映射

<?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="db.Dao.EmployeeDao">
    <!--主鍵查詢-->
    <select id="queryByEmplId" resultType="db.Domain.Employee">
        select * from Employee where emplId=#{emplId}
    </select>
    <!--條件查詢-->
    <select id="queryListBySalary" resultType="db.Domain.Employee" >
        select * from Employee where salary BETWEEN #{start} and #{end}
    </select>
    <!--新增-->
    <insert id="insert" parameterType="db.Domain.Employee">
        insert into employee(emplId,`name`,gender,hireDate,salary) values(#{emplId},#{name},#{gender},#{hireDate},#{salary})
    </insert>
    <!--修改-->
    <update id="update" parameterType="db.Domain.Employee">
        update employee set `name`=#{name},gender=#{gender},salary=#{salary} where emplId=#{emplId}
    </update>
    <delete id="delete">
        delete from employee where emplId=#{emplId}
    </delete>
</mapper>

3.4、主配置文件引用Mapper文件

通過resource屬性指向表的Mapper文件

見2內紅色標註代碼:

3.5、測試代碼

import db.Dao.EmployeeDao;
import db.Domain.Employee;
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 org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.util.List;

public class myTest {
    @Test
    public void TestMyBaisc() throws IOException {
        //1 讀取配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //2 構建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //3 構建SqlSession,並執行mapper內操作
        try (SqlSession session = sqlSessionFactory.openSession()) {
            //獲取接口代理實現
            EmployeeDao dao = session.getMapper(EmployeeDao.class);
            //單數據查詢
            {
                System.out.println("==單數據查詢");
                Employee empl = dao.queryByEmplId("001");
                System.out.println(empl.toString());
            }
            //數據刪除
            {
                dao.delete("004");
                session.commit();
            }
            //數據新增
            {
                System.out.println("==數據新增");
                Employee empl = new Employee();
                empl.setEmplId("004");
                empl.setName("李曉明");
                empl.setGender("男");
                empl.setHireDate(new Date(2020,10,10));
                empl.setSalary(2000);
                int result = dao.insert(empl);
                session.commit();
                System.out.println("行數:"+result);
            }
            //多數據查詢
            {
                System.out.println("==多數據查詢");
                List<Employee> list = dao.queryListBySalary(20,5000);
                for (Employee item : list) {
                    System.out.println(item.toString());
                }
            }
            //數據修改
            {
                System.out.println("==數據新增");
                Employee empl = new Employee();
                empl.setEmplId("003");
                empl.setName("劉超");
                empl.setGender("男");
                empl.setHireDate(new Date(2020,10,10));
                empl.setSalary(2000);
                int result = dao.update(empl);
                session.commit();
                System.out.println("行數:"+result);
            }
            //多數據查詢
            {
                System.out.println("==多數據查詢 - 修改後");
                List<Employee> list = dao.queryListBySalary(20,5000);
                for (Employee item : list) {
                    System.out.println(item.toString());
                }
            }
        }
        System.out.println("測試完成1");
    }
}

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章