博客
关于我
原生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_real_connect 参数注意
    查看>>
    mysql_secure_installation初始化数据库报Access denied
    查看>>
    MySQL_西安11月销售昨日未上架的产品_20161212
    查看>>
    Mysql——深入浅出InnoDB底层原理
    查看>>
    MySQL“被动”性能优化汇总
    查看>>
    MySQL、HBase 和 Elasticsearch:特点与区别详解
    查看>>
    MySQL、Redis高频面试题汇总
    查看>>
    MYSQL、SQL Server、Oracle数据库排序空值null问题及其解决办法
    查看>>
    mysql一个字段为空时使用另一个字段排序
    查看>>
    MySQL一个表A中多个字段关联了表B的ID,如何关联查询?
    查看>>
    MYSQL一直显示正在启动
    查看>>
    MySQL一站到底!华为首发MySQL进阶宝典,基础+优化+源码+架构+实战五飞
    查看>>
    MySQL万字总结!超详细!
    查看>>
    Mysql下载以及安装(新手入门,超详细)
    查看>>
    MySQL不会性能调优?看看这份清华架构师编写的MySQL性能优化手册吧
    查看>>
    MySQL不同字符集及排序规则详解:业务场景下的最佳选
    查看>>
    Mysql不同官方版本对比
    查看>>
    MySQL与Informix数据库中的同义表创建:深入解析与比较
    查看>>
    mysql与mem_细说 MySQL 之 MEM_ROOT
    查看>>
    MySQL与Oracle的数据迁移注意事项,另附转换工具链接
    查看>>