简单的java(非springboot)程序集成mybatis(通过Java原生http请求HttpURLConnection请求接口)

简单的java(非springboot)程序集成mybatis(通过Java原生http请求HttpURLConnection请求接口)

1.pom.xml 文件中引入(非maven项目可下载jar包引入)

		<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
        <!--资源打包-->
        <build>
	        <resources>
	            <resource>
	                <directory>src/main/java</directory>
	                <includes>
	                    <include>**/*.xml</include>
	                </includes>
	            </resource>
	        </resources>
    	</build>

2.resources目录下新建 application.properties(文件名随意) 文件

# 数据库源配置
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/emaildb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=root

3.编写controller层(网址调用)

package com.gremlin.controller;

import com.gremlin.mapper.EmailMapper;
import com.gremlin.pojo.EmailPojo;
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.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @className: EmailController
 * @author: gremlin
 * @version: 1.0.0
 * @description:
 * @date: 2022/5/16 20:03
 */

public class EmailController {
    public static void main(String[] args) {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 然后根据 sqlSessionFactory 得到 session
        SqlSession session = sqlSessionFactory.openSession();

        EmailMapper mapper = session.getMapper(EmailMapper.class);
        List<EmailPojo> emailPojo = mapper.selectEmailInfo();
        emailPojo.forEach(System.out::println);
        String url = "http://localhost:8088/power/selectUser";
        System.out.println(requestUrl(url,""));

    }

    /**
     * 地址请求
     */
    private static String requestUrl(String url,String param) {

        StringBuffer result = new StringBuffer();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        BufferedReader reader = null;
        HttpURLConnection connect = null;
        try {
            // 创建url
            URL reqUrl = new URL(url);
            // 打开连接
            connect = (HttpURLConnection) reqUrl.openConnection();
            // 设置请求方式
            connect.setRequestMethod("POST");
            // 设置是否可读取
            /**
             * DoOutput设置是否向httpUrlConnection输出
             * DoInput设置是否从httpUrlConnection读入
             * 发送post请求必须设置这两个
             */
            connect.setDoOutput(true);
            connect.setDoInput(true);
            // 设置连接超时时间
            connect.setConnectTimeout(15000);
            //设置读取超时时间
            // connect.setReadTimeout(15000);

            // 设置是否启动缓存
            connect.setUseCaches(false);
            connect.setInstanceFollowRedirects(true);
            //设置通用的请求属性(入参数的格式)
            connect.setRequestProperty("accept", "*/*");
            connect.setRequestProperty("connection", "Keep-Alive");
            connect.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            connect.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //拼装参数
            if (null != param && !"".equals(param)) {
                //设置参数
                outputStream = connect.getOutputStream();
                //拼装参数
                outputStream.write(param.getBytes(StandardCharsets.UTF_8));
            }

            //开始连接
            connect.connect();

            //获取响应数据
            if (connect.getResponseCode() == 200) {
                //获取返回的数据
                inputStream = connect.getInputStream();
                if (null != inputStream) {
                    reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                    String temp = null;
                    while (null != (temp = reader.readLine())) {
                        result.append(temp);
                        result.append("\r\n");
                    }
                }
            }else if (connect.getResponseCode() == 405){
                return "请求方式错误";
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭远程连接
            if (null != connect) {
                connect.disconnect();
            }
        }
        return result.toString();
    }
}

4.src目录下新建mapper下新建Mapper接口类

package com.gremlin.mapper;

import com.gremlin.pojo.EmailPojo;

import java.util.List;

/**
 * @className: EmailMapper
 * @author: gremlin
 * @version: 1.0.0
 * @description:
 * @date: 2022/5/16 19:47
 */
public interface EmailMapper {
    List<EmailPojo> selectEmailInfo();
}

5.新建实体类

package com.gremlin.pojo;

import lombok.Data;

/**
 * @className: EmailPojo
 * @author: gremlin
 * @version: 1.0.0
 * @description:
 * @date: 2022/5/16 19:25
 */
@Data
public class EmailPojo {
    private String url;
    private String startTime;
    private String endTime;
    private String riskModule;
    private Integer status;
    private String depict;
    private Integer tempStatus;
}

6.在resources目录下新建mapper目录下新建xml文件(或直接可放在src下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="com.gremlin.mapper.EmailMapper">

    <select id="selectEmailInfo" resultType="com.gremlin.pojo.EmailPojo">
        SELECT
            t.url url,
            t.start_time startTime,
            t.end_time endTime,
            t.risk_module riskModule,
            t.`status` status,
            t.desp depict,
            t.temp_status tempStatus
        FROM t_email_url t
        WHERE 1 = 1
    </select>
</mapper>

或可下载源码 https://gitee.com/fantasy-starry/java_mybatis_demo.git
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值