博客
关于我
原生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学习-group by和having
    查看>>
    MySQL学习-MySQL数据库事务
    查看>>
    MySQL学习-MySQL条件查询
    查看>>
    MySQL学习-SQL语句的分类与MySQL简单查询
    查看>>
    MySQL学习-子查询及limit分页
    查看>>
    MySQL学习-排序与分组函数
    查看>>
    MySQL学习-连接查询
    查看>>
    Mysql学习总结(10)——MySql触发器使用讲解
    查看>>
    Mysql学习总结(12)——21分钟Mysql入门教程
    查看>>
    Mysql学习总结(15)——Mysql错误码大全
    查看>>
    Mysql学习总结(19)——Mysql无法创建外键的原因
    查看>>
    Mysql学习总结(21)——MySQL数据库常见面试题
    查看>>
    Mysql学习总结(22)——Mysql数据库中制作千万级测试表
    查看>>
    Mysql学习总结(23)——MySQL统计函数和分组查询
    查看>>
    Mysql学习总结(24)——MySQL多表查询合并结果和内连接查询
    查看>>