博客
关于我
原生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中的 +号 和 CONCAT(str1,str2,...)
    查看>>
    Mysql中的 IFNULL 函数的详解
    查看>>
    mysql中的collate关键字是什么意思?
    查看>>
    MySql中的concat()相关函数
    查看>>
    mysql中的concat函数,concat_ws函数,concat_group函数之间的区别
    查看>>
    MySQL中的count函数
    查看>>
    MySQL中的DB、DBMS、SQL
    查看>>
    MySQL中的DECIMAL类型:MYSQL_TYPE_DECIMAL与MYSQL_TYPE_NEWDECIMAL详解
    查看>>
    MySQL中的GROUP_CONCAT()函数详解与实战应用
    查看>>
    MySQL中的IO问题分析与优化
    查看>>
    MySQL中的ON DUPLICATE KEY UPDATE详解与应用
    查看>>
    mysql中的rbs,SharePoint RBS:即使启用了RBS,内容数据库也在不断增长
    查看>>
    mysql中的undo log、redo log 、binlog大致概要
    查看>>
    Mysql中的using
    查看>>
    MySQL中的关键字深入比较:UNION vs UNION ALL
    查看>>
    mysql中的四大运算符种类汇总20多项,用了三天三夜来整理的,还不赶快收藏
    查看>>
    mysql中的字段如何选择合适的数据类型呢?
    查看>>
    MySQL中的字符集陷阱:为何避免使用UTF-8
    查看>>