博客
关于我
原生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 如何给SQL添加索引
    查看>>
    mysql 字段区分大小写
    查看>>
    mysql 字段合并问题(group_concat)
    查看>>
    mysql 字段类型类型
    查看>>
    MySQL 字符串截取函数,字段截取,字符串截取
    查看>>
    MySQL 存储引擎
    查看>>
    mysql 存储过程 注入_mysql 视图 事务 存储过程 SQL注入
    查看>>
    MySQL 存储过程参数:in、out、inout
    查看>>
    mysql 存储过程每隔一段时间执行一次
    查看>>
    mysql 存在update不存在insert
    查看>>
    Mysql 学习总结(86)—— Mysql 的 JSON 数据类型正确使用姿势
    查看>>
    Mysql 学习总结(87)—— Mysql 执行计划(Explain)再总结
    查看>>
    Mysql 学习总结(88)—— Mysql 官方为什么不推荐用雪花 id 和 uuid 做 MySQL 主键
    查看>>
    Mysql 学习总结(89)—— Mysql 库表容量统计
    查看>>
    mysql 实现主从复制/主从同步
    查看>>
    mysql 审核_审核MySQL数据库上的登录
    查看>>
    mysql 导入 sql 文件时 ERROR 1046 (3D000) no database selected 错误的解决
    查看>>
    mysql 导入导出大文件
    查看>>
    mysql 将null转代为0
    查看>>
    mysql 常用
    查看>>