目录
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对象)映射成数据库中的记录。