从JDBC到MyBatis

Mybatis与JDBC

一、JDBC

1.新建IDEA项目

在这里插入图片描述
新建java class
在这里插入图片描述
代码如下

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DatebaseLink {
//mysql8.0以上版本
    static final String driverName="com.mysql.cj.jdbc.Driver";
    static final String dbUrl= "jdbc:mysql://localhost:3306/text?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
    //账号密码自行设置
    static final String userName="root";
    static final String password="maifov123";
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            // 注册 JDBC 驱动
            Class.forName(driverName);

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(dbUrl,userName,password);

            // 执行查询
            System.out.println(" 实例化Statement对象...");
            stmt = (Statement) conn.createStatement();
            String sql;
            sql = "SELECT id, name, password, email FROM users";
            ResultSet rs = stmt.executeQuery(sql);

            // 展开结果集数据库
            while(rs.next()){
                // 通过字段检索
                int id  = rs.getInt("id");
                String name = rs.getString("name");
                String password = rs.getString("password");
                String email = rs.getString("email");
                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", 姓名: " + name);
                System.out.print(", 密码: " +password);
                System.out.print(", 邮箱: " +email);
                System.out.print("\n");
            }
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        }catch(SQLException se){
            // 处理 JDBC 错误
            se.printStackTrace();
        }catch(Exception e){
            // 处理 Class.forName 错误
            e.printStackTrace();
        }finally{
            // 关闭资源
            try{
                if(stmt!=null) stmt.close();
            }catch(SQLException se2){
            }// 什么都不做
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

2.导入JDBC的jar包

在这里插入图片描述

在这里插入图片描述

3.使用JDBC运行

结果:
在这里插入图片描述

二、MyBatis

1.新建idea项目

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

2.配置application.properties

在这里插入图片描述

server.port=8080
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
//账号密码自定
spring.datasource.username=root
spring.datasource.password=maifov123
mybatis.mapper-locations=classpath:mapper/*Mapper.xml

3.代码编写

在这里插入图片描述
1

package com.example.datebasedemo.controller;
import com.example.datebasedemo.entity.Student;
import com.example.datebasedemo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/Student")
class UserController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("/getAllStudent")
    public List<Student> findAll(){
        return studentService.findAllStudent();
    }

    @RequestMapping("/getStudentByno/{no}")
    public List<Student> findUserByStudentId(@PathVariable int no){
        return studentService.findStudentByno(no);
    }
}

2

package com.example.datebasedemo.entity;

public class Student {
    private int no;
    private String name;
    private int age;

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

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

    public String getName() {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }

}

3

package com.example.datebasedemo.mapper;
import com.example.datebasedemo.entity.Student;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface StudentMapper {
    public List<Student> findAllStudent();

    List<Student> findStudentByno(int no);
}

4

package com.example.datebasedemo.service;

import com.example.datebasedemo.entity.Student;
import com.example.datebasedemo.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class StudentService {
    @Autowired(required = false)
    public StudentMapper studentMapper;
    public List<Student> findAllStudent() {
        return studentMapper.findAllStudent();
    }

    public List<Student> findStudentByno(int no) {
        return studentMapper.findStudentByno(no);
    }
}

5

<?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.example.databasedemo.mapper.StudentMapper">
    <resultMap id="result" type="com.example.databasedemo.entity.Student">
        <result column="no" jdbcType="INTEGER" property="no" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="age" jdbcType="INTEGER" property="age" />
    </resultMap>

    <select id="findAllStudent" resultType="com.example.databasedemo.entity.Student">
        select  * from student;
    </select>

    <select id="findStudentByno" resultType="com.example.databasedemo.entity.Student">
        select * from student where no=#{no};
    </select>
</mapper>

4.运行结果

在这里插入图片描述

在这里插入图片描述

小结

MyBatis 避免了几乎所有的
JDBC代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的XML或注
解,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

MyBatis-从JDBC到Spring整合MyBatis

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值