Mybatis学习

正式进入框架学习

一 . 环境搭建及测试

1 . 导入依赖

在IDEA中创建一个maven项目

在根目录的 pom.xml 文件夹下导入依赖 mybatis mysql junit

<!--导入依赖-->
    <dependencies>
        <!--   mybatis     -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

        <!--   mysql     -->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

        <!--   junit     -->
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

2 . mapper文件

src --> main --> resources 下创建 mybatis-config.xml 文件

此文件是连接数据库 和 让Mybatis扫描对应的mapper文件

<?xml version="1.0" encoding="UTF8" ?>
<!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://localhost:3306/atanycosts?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>

    </environments>
    <mappers>
        <mapper resource="mapper/userMapper.xml"/>
    </mappers>

</configuration>

再 在src --> main --> resources 下创建 mapper 文件夹,里创建 userMapper.xml 文件

此文件里写的是 SQL语句

<?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="UserEntity">
    <select id="getByUsers" resultType="com.atanycosts.entity.UserEntity">
        select * from user
    </select>
</mapper>

3 . 实体类

src --> main --> com --> atanycosts --> entity

写入对应数据库的字段

package com.atanycosts.entity;

//实体类
public class UserEntity {
    private Long id;
    private String name;
    private String address;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "UserEntity{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

4 . Test类

package atanycosts.dao;

import com.atanycosts.entity.UserEntity;
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.util.List;

public class UserdaoTest {

    @Test
    public void test() throws IOException {
        // 1.读取加载mybatis-config.xml
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 2.获取到获取到
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 3.根据 mapper id=getByUsers 执行该s  ql 语句 通过  sql语句得到我们的对象 orm
        List<UserEntity> userEntitys = sqlSession.selectList("getByUsers", UserEntity.class);
        System.out.println(userEntitys);
        sqlSession.close();
    }
}

二 . Mapper 代理开发模式

1 . 在实体类层

创建 UserFlight

package com.atanycosts.entity;

import java.util.Date;

//UserFlight实体类
public class UserFlight {
    private Integer id;    //id
    private String flight_id ;    //航号
    private String company ;    //航空公司
    private String departure_airport ;  //出发机场
    private String arrive_airport ; //达到机场
    private Date departure_time;    //出发时间
    private Date arrive_time;   //到达时间
    private String model;   //机型
    private Integer is_delete;  //是否隐藏0显示 1隐藏

    public Integer getId() {
        return id;
    }

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

    public String getFlight_id() {
        return flight_id;
    }

    public void setFlight_id(String flight_id) {
        this.flight_id = flight_id;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getDeparture_airport() {
        return departure_airport;
    }

    public void setDeparture_airport(String departure_airport) {
        this.departure_airport = departure_airport;
    }

    public String getArrive_airport() {
        return arrive_airport;
    }

    public void setArrive_airport(String arrive_airport) {
        this.arrive_airport = arrive_airport;
    }

    public Date getDeparture_time() {
        return departure_time;
    }

    public void setDeparture_time(Date departure_time) {
        this.departure_time = departure_time;
    }

    public Date getArrive_time() {
        return arrive_time;
    }

    public void setArrive_time(Date arrive_time) {
        this.arrive_time = arrive_time;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public Integer getIs_delete() {
        return is_delete;
    }

    public void setIs_delete(Integer is_delete) {
        this.is_delete = is_delete;
    }
    
}

2 . 创建mapper层

并创建 getByFlightAll getByFlightID 接口

src --> main --> com --> atanycosts --> mapper -->UserMapper

package com.atanycosts.mapper;

import com.atanycosts.entity.UserEntity;
import com.atanycosts.entity.UserFlight;

import java.util.List;

public interface UserMapper {

    List<UserEntity> getByUsers();  //环境测试接口
    List<UserFlight> getByFlightAll();  //航班接口
    UserFlight getByFlightID(Integer id);   //获取对应ID

}

3 . 创建service层

src --> main --> com --> atanycosts --> service -->FlightService

package com.atanycosts.service;

import com.atanycosts.entity.UserFlight;
import com.atanycosts.mapper.UserMapper;
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;
import java.util.List;

//flight业务逻辑层
public class FlightService {
    private UserMapper flightMapper;
    private SqlSession sqlSession;

    public FlightService() throws IOException {
        // 1.读取加载mybatis-config.xml
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 2.获取到获取到
        sqlSession = sqlSessionFactory.openSession();
        flightMapper = sqlSession.getMapper(UserMapper.class);
        // sqlSession.close();
    }

    /**
     * 获取所有
     * @return
     */
    public List<UserFlight> getByFlightAll(){
        return flightMapper.getByFlightAll();
    }

    /**
     * 获取对应ID
     * @param id
     * @return
     */
    public UserFlight getByFlightID(Integer id){
        return flightMapper.getByFlightID(id);
    }
}

4 . 在测试类中创建对应方法

package atanycosts.dao;

import com.atanycosts.entity.UserEntity;
import com.atanycosts.entity.UserFlight;
import com.atanycosts.mapper.UserMapper;
import com.atanycosts.service.FlightService;
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.util.Date;
import java.util.List;

public class UserdaoTest {

    /**
     * 环境测试
     *
     * @throws IOException
     */
    @Test
    public void test01() throws IOException {
        // 1.读取加载mybatis-config.xml
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        /**
         * 接口
         * getByUsers
         */
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<UserEntity> byUsers = mapper.getByUsers();
        System.out.println(byUsers);

        sqlSession.close();
    }

    /**
     * flight测试
     * 获取所有
     *
     * @throws IOException
     */
    @Test
    public void test02() throws IOException {
        FlightService flightService = new FlightService();
        List<UserFlight> byFlightAll = flightService.getByFlightAll();
        System.out.println(byFlightAll);
        // sqlSession.close();
    }

    /**
     * flight测试
     * 获取对应ID
     *
     * @throws IOException
     */
    @Test
    public void getByUsersID() throws IOException {
        FlightService flightService = new FlightService();
        UserFlight byFlightID = flightService.getByFlightID(1);
        System.out.println(byFlightID);
    }
}

5 . 对应的SQL

<?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.atanycosts.mapper.UserMapper">
    <select id="getByFlightAll" resultType="com.atanycosts.entity.UserFlight">
        select *
        from flight
    </select>
    
    <select id="getByFlightID" resultType="com.atanycosts.entity.UserFlight" parameterType="int">
        select *
        from flight
        where id = #{id}
    </select>
</mapper>

当数据库的字段与Java的属性对应不上时在userMapper.xml下写入如下代码

column 数据库字段 property Java属性

id id 包裹

其他用 result

<resultMap id="test" type="com.atanycosts.entity.UserEntity">
        <id column="id" property="id"></id>
        <result column="Database Field" property="Java property"></result>
</resultMap>

三 . 增删改查

1 . 实体类

实体类中构造增删改所需要的方法

/**
     * 插入数据
     * @param flight_id
     * @param company
     * @param departure_airport
     * @param arrive_airport
     * @param departure_time
     * @param arrive_time
     * @param model
     * @param is_delete
     */
    public UserFlight(String flight_id, String company, String departure_airport, String arrive_airport, Date departure_time, Date arrive_time, String model, Integer is_delete) {
        this.flight_id = flight_id;
        this.company = company;
        this.departure_airport = departure_airport;
        this.arrive_airport = arrive_airport;
        this.departure_time = departure_time;
        this.arrive_time = arrive_time;
        this.model = model;
        this.is_delete = is_delete;
    }

    /**
     * 更新数据
     * @param id
     * @param flight_id
     * @param company
     * @param departure_airport
     * @param arrive_airport
     * @param departure_time
     * @param arrive_time
     * @param model
     * @param is_delete
     */
    public UserFlight(Integer id, String flight_id, String company, String departure_airport, String arrive_airport, Date departure_time, Date arrive_time, String model, Integer is_delete) {
        this.id = id;
        this.flight_id = flight_id;
        this.company = company;
        this.departure_airport = departure_airport;
        this.arrive_airport = arrive_airport;
        this.departure_time = departure_time;
        this.arrive_time = arrive_time;
        this.model = model;
        this.is_delete = is_delete;
    }

    /**
     * 删除数据
     * @param id
     */
    public UserFlight(Integer id) {
        this.id = id;
    }

2 . 在接口文件中写入

/**
     * 插入数据
     * @param userFlight
     * @return
     */
    boolean insertFlight(UserFlight userFlight);

    /**
     * 修改数据
     * @param userFlight
     * @return
     */
    boolean updateFlight(UserFlight userFlight);

    /**
     * 删除数据
     * @param userFlight
     * @return
     */
    boolean deleteByIdFlight(UserFlight userFlight);

3 . 在Service层写入

/**
     * 插入数据
     * @param userFlight
     * @return
     */
    public boolean insertFlight(UserFlight userFlight){
        // 艹了 , 插入时 , 要提交事务
        boolean result = flightMapper.insertFlight(userFlight);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

    /**
     * 更新数据
     * @param userFlight
     * @return
     */
    public boolean updateFlight(UserFlight userFlight){
        boolean result = flightMapper.updateFlight(userFlight);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

    /**
     * 删除数据
     * @param userFlight
     * @return
     */
    public boolean deleteByIdFlight(UserFlight userFlight){
        boolean result = flightMapper.deleteByIdFlight(userFlight);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

4 . 测试类

/**
     * flight测试
     * 插入数据
     *
     * @throws IOException
     */
    @Test
    public void insertFlight() throws IOException {
        FlightService flightService = new FlightService();
        UserFlight userFlight = new UserFlight("1", "1", "1", "1", new Date(), new Date(), "1", 0);
        boolean b = flightService.insertFlight(userFlight);
        System.out.println(b);
    }

    /**
     * flight测试
     * 更新数据
     *
     * @throws IOException
     */
    @Test
    public void updateFlight() throws IOException {
        FlightService flightService = new FlightService();
        UserFlight userFlight = new UserFlight(12, "2", "2", "2", "2", new Date(), new Date(), "更改成功", 0);
        boolean b = flightService.updateFlight(userFlight);
        System.out.println(b);
    }

    /**
     * 删除数据
     *
     * @throws IOException
     */
    @Test
    public void deleteByIdFlight() throws IOException {
        FlightService flightService = new FlightService();
        UserFlight userFlight = new UserFlight(13);
        boolean b = flightService.deleteByIdFlight(userFlight);
        System.out.println(b);
    }

5 . 对应的SQL

<!-- userMapper.xml文件 -->
    <insert id="insertFlight" parameterType="com.atanycosts.entity.UserFlight" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO atanycosts.flight (`id`, `flight_id`, `company`, `departure_airport`, `arrive_airport`,`departure_time`, `arrive_time`, `model`, `is_delete`) VALUES (null, #{flight_id}, #{company}, #{departure_airport}, #{arrive_airport}, #{departure_time},#{arrive_time}, #{model}, #{is_delete});
    </insert>

    <update id="updateFlight" parameterType="com.atanycosts.entity.UserFlight">
        UPDATE atanycosts.flight
        SET `id`=#{id},
            `flight_id`=#{flight_id},
            `company`=#{company},
            `departure_airport`=#{departure_airport},
            `arrive_airport`=#{arrive_airport},
            `departure_time`=#{departure_time},
            `arrive_time`=#{arrive_time},
            `model`=#{model},
            `is_delete`=#{is_delete}
        WHERE (`id` = #{id});
    </update>

    <delete id="deleteByIdFlight" parameterType="int">
        delete from atanycosts.flight where id=#{id};
    </delete>

四 . 映射文件标签

五 . 多条件查询

六 . 注解开发

最后修改:2022 年 11 月 28 日
如果觉得我的文章对你有用,请随意赞赏