Java笔记:JDBC传统数据库访问和SpringData入门(1)

简介: Java笔记:JDBC传统数据库访问和SpringData入门

一、SpringData简介

SpringData提供一致的,大家都熟悉的编程模型,为了简化数据库的访问。

子项目:

Spring Data JPA:减少数据层的开发量

Spring Data Mongo DB:基于分布式数据层的数据库,在大数据层用的比较多

Spring Data Redis:开源,由C语言编写的,支持网络、内存,而且可以持久化的,提供非常多的语言支持

Spring Data Solr:高性能 搜索功能 对查询性能优化

二、传统方式访问数据库

1、JDBC

  • Connection
  • Statement
  • ResultSet
  • TestCase

项目准备

  1. 新建maven 项目
  2. 选择maven-archetype-quickstart
  3. 设置GAV
  4. 添加依赖:
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.20</version>
</dependency>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
  1. 数据库
create database spring_data;
create table student(
    id int not null auto_increment,
    name varchar(20) not null,
    age int not null,
    primary key(id)
);
insert into student(name, age) values("刘备", 40);
insert into student(name, age) values("关羽", 30);
insert into student(name, age) values("张飞", 20);

开发JDBCUtil工具类

获取Connection,关闭Connection,Statement,ResultSet

db.properties


jdbc.driverClass = com.mysql.cj.jdbc.Driver

jdbc.username = root

jdbc.password = 123456

jdbc.url = jdbc:mysql://127.0.0.1:3306/data

package com.mouday.util;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
 * JDBC工具类
 * 1. 获取Connection
 * 2. 释放资源
 */
public class JDBCUtil {
    // 配置型内容建议放在配置文件中
    private static final String driverClass = "com.mysql.cj.jdbc.Driver";
    private static final String username = "root";
    private static final String password = "123456";
    private static final String url = "jdbc:mysql://127.0.0.1:3306/data";
    /**
     * 获取Connection
     *
     * @return
     */
    public static Connection getConnection() throws Exception {
        // 读取配置文件
        InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        String driverClass = properties.getProperty("jdbc.driverClass");
        String username = properties.getProperty("jdbc.username");
        String password = properties.getProperty("jdbc.password");
        String url = properties.getProperty("jdbc.url");
        Class.forName(driverClass);
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }
    /**
     * 关闭链接
     *
     * @param resultSet
     * @param statement
     * @param connection
     */
    public static void release(ResultSet resultSet,
                               Statement statement,
                               Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

注意事项:

配置的属性放在配置文件中

实体类

package com.mouday.domain;
/**
 * 学生实体类
 */
public class Student {
    private Integer id;
    private String  name;
    private Integer age;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

接口类

package com.mouday.dao;
import com.mouday.domain.Student;
import java.util.List;
/**
 * 学生访问接口
 */
public interface StudentDao {
    /**
     * 获取所有学生
     * @return
     */
    List<Student> query();
    /**
     * 插入数据
     * @param student
     * @return
     */
    Integer insert(Student student);
}

实现类

package com.mouday.dao.impl;
import com.mouday.dao.StudentDao;
import com.mouday.domain.Student;
import com.mouday.util.JDBCUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
 * 学生访问接口实现类
 */
public class StudentDaoImpl implements StudentDao {
    @Override
    public List<Student> query() {
        List<Student> students = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        String sql = "select id, name, age from student";
        Student student;
        try {
            connection = JDBCUtil.getConnection();
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Integer id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                Integer age = resultSet.getInt("age");
                student = new Student();
                student.setId(id);
                student.setName(name);
                student.setAge(age);
                students.add(student);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(resultSet, statement, connection);
        }
        return students;
    }
    @Override
    public Integer insert(Student student) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        String sql = "insert into student (name, age) values (?, ?)";
        Integer id = null;
        try {
            connection = JDBCUtil.getConnection();
            statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            statement.setString(1, student.getName());
            statement.setInt(2, student.getAge());
            statement.executeUpdate();
            // 获取自增id
            resultSet = statement.getGeneratedKeys();
            if (resultSet.next()) {
                id = resultSet.getInt(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(resultSet, statement, connection);
        }
        return id;
    }
}

测试类

package com.mouday.util;
import org.junit.Assert;
import org.junit.Test;
import java.sql.Connection;
public class JDBCUtilTest {
    @Test
    public void  testGetConnection() throws Exception{
        Connection connection = JDBCUtil.getConnection();
        Assert.assertNotNull(connection);
    }
}
package com.mouday.dao.impl;
import com.mouday.dao.StudentDao;
import com.mouday.domain.Student;
import org.junit.Test;
import java.util.List;
public class StudentDaoImplTest {
    @Test
    public void testQuery() {
        StudentDao studentDao = new StudentDaoImpl();
        List<Student> students = studentDao.query();
        System.out.println(students);
    }
    @Test
    public void testInsert() {
        StudentDao studentDao = new StudentDaoImpl();
        Student student = new Student();
        student.setName("曹操");
        student.setAge(50);
        Integer id = studentDao.insert(student);
        System.out.println(id);
    }
}
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
2月前
|
SQL Java 数据库连接
除了JDBC,还有哪些常见的数据库访问技术?
除了JDBC,还有哪些常见的数据库访问技术?
284 2
|
2月前
|
Java 开发工具
【Azure Storage Account】Java Code访问Storage Account File Share的上传和下载代码示例
本文介绍如何使用Java通过azure-storage-file-share SDK实现Azure文件共享的上传下载。包含依赖引入、客户端创建及完整示例代码,助你快速集成Azure File Share功能。
379 5
|
2月前
|
存储 Oracle Java
java零基础学习者入门课程
本课程为Java零基础入门教程,涵盖环境搭建、变量、运算符、条件循环、数组及面向对象基础,每讲配示例代码与实践建议,助你循序渐进掌握核心知识,轻松迈入Java编程世界。
316 0
|
3月前
|
Java
java入门代码示例
本文介绍Java入门基础,包含Hello World、变量类型、条件判断、循环及方法定义等核心语法示例,帮助初学者快速掌握Java编程基本结构与逻辑。
424 0
|
3月前
|
前端开发 Java 数据库连接
帮助新手快速上手的 JAVA 学习路线最详细版涵盖从入门到进阶的 JAVA 学习路线
本Java学习路线涵盖从基础语法、面向对象、异常处理到高级框架、微服务、JVM调优等内容,适合新手入门到进阶,助力掌握企业级开发技能,快速成为合格Java开发者。
573 3
|
3月前
|
Java API 数据库
2025 年最新 Java 实操学习路线,从入门到高级应用详细指南
2025年Java最新实操学习路线,涵盖从环境搭建到微服务、容器化部署的全流程实战内容,助你掌握Java 21核心特性、Spring Boot 3.2开发、云原生与微服务架构,提升企业级项目开发能力,适合从入门到高级应用的学习需求。
787 0
|
3月前
|
缓存 关系型数据库 BI
使用MYSQL Report分析数据库性能(下)
使用MYSQL Report分析数据库性能
165 3
|
3月前
|
关系型数据库 MySQL 数据库
自建数据库如何迁移至RDS MySQL实例
数据库迁移是一项复杂且耗时的工程,需考虑数据安全、完整性及业务中断影响。使用阿里云数据传输服务DTS,可快速、平滑完成迁移任务,将应用停机时间降至分钟级。您还可通过全量备份自建数据库并恢复至RDS MySQL实例,实现间接迁移上云。
|
3月前
|
关系型数据库 MySQL 数据库
阿里云数据库RDS费用价格:MySQL、SQL Server、PostgreSQL和MariaDB引擎收费标准
阿里云RDS数据库支持MySQL、SQL Server、PostgreSQL、MariaDB,多种引擎优惠上线!MySQL倚天版88元/年,SQL Server 2核4G仅299元/年,PostgreSQL 227元/年起。高可用、可弹性伸缩,安全稳定。详情见官网活动页。
802 152
|
3月前
|
关系型数据库 MySQL 分布式数据库
阿里云PolarDB云原生数据库收费价格:MySQL和PostgreSQL详细介绍
阿里云PolarDB兼容MySQL、PostgreSQL及Oracle语法,支持集中式与分布式架构。标准版2核4G年费1116元起,企业版最高性能达4核16G,支持HTAP与多级高可用,广泛应用于金融、政务、互联网等领域,TCO成本降低50%。

热门文章

最新文章