博客
关于我
原生servlet——如何连接数据库
阅读量:599 次
发布时间:2019-03-12

本文共 5502 字,大约阅读时间需要 18 分钟。

项目结构与数据库配置

在开发一个基于 JDBC 的数据访问层时,确保项目结构清晰和数据库配置正确是实现CRUD操作的关键。

一、项目结构

按照功能模块划分包,确保类似下面结构:

com├── dao│   ├── impl│   │   ├── BaseDao.java│   │   └── StudentDao.java│   └── model│       ├── entity│       │   └── Student.java│       └── domain│           └── StudentDomain.java

二、数据库配置

确保 jdbc.properties 中有正确的数据库配置:

username=rootpassword=1234url=jdbc:mysql://localhost:3306/peixun?characterEncoding=UTF-8driverClassName=com.mysql.jdbc.Driver

三、通用数据访问接口

实现通用数据访问接口尽量减少代码重复:

package com.dao;public interface BaseDao
{
T selectForOne(Class, String, Object... args); List selectForMore(Class, String, Object... args); int update(String, Object... args);}

项目实现步骤

一、创建项目框架

  • 建立位置结构
  • mkdir -p src/main/java/com/dao/implmkdir -p src/main/java/com/model/entity

    二、配置数据库

  • 编写 jdbc.properties
  • username=rootpassword=1234url=jdbc:mysql://localhost:3306/peixundriverClassName=com.mysql.jdbc.Driver
    1. 编写 JdbcUtils 工具类
    2. package com.utils;import com.mysql.jdbc.Driver;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import org.apache.commons.dbutils.handlers.BeanListHandler;import org.springframework.jdbc.datasource.DriverManagerDataSource;import java.sql.DriverManager;import java.sql.SQLException;public class JdbcUtils {    private static ThreadLocal
      dataSource = new ThreadLocal<>(); static { try { ClassLoader classLoader = JdbcUtils.class.getClassLoader(); InputStream is = classLoader.getResourceAsStream("jdbc.properties"); Properties props = new Properties(); props.load(is); dataSource.set((DriverManagerDataSource) DriverManager.createDataSource(props)); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection() { try { return dataSource.get().getConnection(); } catch (SQLException e) { throw new RuntimeException("获取数据库连接失败", e); } } public static void closeConnection(Connection connection) { try { if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } }}

      三、实现通用 BaseDao

      package com.dao.impl;import com.dao.BaseDao;import com.model.entity.Student;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import org.apache.commons.dbutils.handlers.BeanListHandler;import com.utils.JdbcUtils;import java.util.List;import java.sql.Connection;import java.sql.SQLException;public class BaseDao
      implements BaseDao
      { private QueryRunner queryRunner = new QueryRunner(); public T selectForOne(Class
      type, String sql, Object... args) { Connection connection = JdbcUtils.getConnection(); try { return getBean(type, sql, args); } catch (SQLException e) { throw new RuntimeException("获取单条数据失败", e); } finally { JdbcUtils.closeConnection(connection); } } public List
      selectForMore(Class
      type, String sql, Object... args) { Connection connection = JdbcUtils.getConnection(); try { return listBeans(type, sql, args); } catch (SQLException e) { throw new RuntimeException("获取多个数据失败", e); } finally { JdbcUtils.closeConnection(connection); } } private T getBean(Class
      type, String sql, Object... args) { try { return queryRunner.query(JdbcUtils.getConnection(), sql, new BeanHandler
      (type), args); } catch (SQLException e) { throw new RuntimeException("获取对象失败", e); } } private List
      listBeans(Class
      type, String sql, Object... args) { try { return queryRunner.query(JdbcUtils.getConnection(), sql, new BeanListHandler
      (type), args); } catch (SQLException e) { throw new RuntimeException("获取列表失败", e); } } public int update(String sql, Object... args) { Connection connection = JdbcUtils.getConnection(); try { return queryRunner.update(connection, sql, args); } catch (SQLException e) { throw new RuntimeException("执行更新操作失败", e); } finally { JdbcUtils.closeConnection(connection); } return -1; }}

      四、在 StudentDao 中继承 BaseDao

      package com.dao;public interface StudentDao extends BaseDao
      {}

      五、实现 StudentDao

      package com.dao.impl;import com.dao.StudentDao;import com.model.entity.Student;import com.utils.JdbcUtils;public class StudentDao implements StudentDao {}

      测试验证

    3. 创建测试类
    4. package com;import com.dao.impl.BaseDao;import com.dao.StudentDao;import com.model.entity.Student;import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.*;class TestDataAccess {    @Test    void testSelectMore() {        BaseDao
      baseDao = new BaseDao<>(); List
      students = baseDao.selectForMore(Student.class, "SELECT * FROM student"); assertTrue(students.size() > 0); for (Student student : students) { assertEquals("St", student.getName()); } } @Test void testUpdate() { BaseDao
      baseDao = new BaseDao<>(); Student student = new Student(); student.setName("X"); int updated = baseDao.update("UPDATE student SET name = ?", student.getName()); assertEquals(1, updated); }}

      项目部署

      完成以上步骤后,将 Student.javajdbc.properties 打包或部署到服务器。运行单元测试软件,确保所有测试用例通过。

      通过以上步骤,您可以实现一个功能健全的数据库数据访问层,减少代码量并提高代码质量。

    转载地址:http://ohetz.baihongyu.com/

    你可能感兴趣的文章
    Mysql 数据类型一日期
    查看>>
    MySQL 数据类型和属性
    查看>>
    mysql 敲错命令 想取消怎么办?
    查看>>
    Mysql 整形列的字节与存储范围
    查看>>
    mysql 断电数据损坏,无法启动
    查看>>
    MySQL 日期时间类型的选择
    查看>>
    Mysql 时间操作(当天,昨天,7天,30天,半年,全年,季度)
    查看>>
    MySQL 是如何加锁的?
    查看>>
    MySQL 是怎样运行的 - InnoDB数据页结构
    查看>>
    mysql 更新子表_mysql 在update中实现子查询的方式
    查看>>
    MySQL 有什么优点?
    查看>>
    mysql 权限整理记录
    查看>>
    mysql 权限登录问题:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)
    查看>>
    MYSQL 查看最大连接数和修改最大连接数
    查看>>
    MySQL 查看有哪些表
    查看>>
    mysql 查看锁_阿里/美团/字节面试官必问的Mysql锁机制,你真的明白吗
    查看>>
    MySql 查询以逗号分隔的字符串的方法(正则)
    查看>>
    MySQL 查询优化:提速查询效率的13大秘籍(避免使用SELECT 、分页查询的优化、合理使用连接、子查询的优化)(上)
    查看>>
    mysql 查询,正数降序排序,负数升序排序
    查看>>
    MySQL 树形结构 根据指定节点 获取其下属的所有子节点(包含路径上的枝干节点和叶子节点)...
    查看>>