当前位置: 首页 > news >正文

网站服务公司名称潍坊住房公积金管理中心

网站服务公司名称,潍坊住房公积金管理中心,视频线上推广,厦门思明区建设局网站文章目录 JDBC封装DAO模式实体类DAO接口DAO实现类数据源配置基础DAO类业务逻辑层 单例模式饿汉式懒汉式 JDBC封装 JDBC(Java Database Connectivity)封装是一种将 JDBC 的基本操作和常见的数据库访问逻辑封装成易于使用的工具类或框架的方法。这样做的目…

文章目录

    • JDBC封装
    • DAO模式
      • 实体类
      • DAO接口
      • DAO实现类
      • 数据源配置
      • 基础DAO类
      • 业务逻辑层
    • 单例模式
      • 饿汉式
      • 懒汉式

JDBC封装

JDBC(Java Database Connectivity)封装是一种将 JDBC 的基本操作和常见的数据库访问逻辑封装成易于使用的工具类或框架的方法。这样做的目的是为了减少重复代码,提高代码的可读性和可维护性,并且简化数据库访问的过程。

在这里插入图片描述

隔离业务逻辑代码和数据访问代码
隔离不同数据库的实现

实现 JDBC 封装

  • 将所有增删改查操作抽取成接口
  • 定义实体类传输数据
  • 将通用的操作(打开、关闭连接等)封装到工具类
  • 数据库工具类BaseDao:增、删、改、查的通用方法

DAO模式

DAO(Data Access Object 数据存取对象)模式:将数据访问逻辑封装在单独的类中,使得业务逻辑层不需要关心具体的数据库操作细节。

  • DAO接口:定义了对数据库进行访问的方法
  • DAO实现类:实现了DAO接口,提供了具体的数据访问逻辑
  • 实体类:表示数据库中的表或记录
  • 数据源配置:配置数据库连接信息
  • 业务逻辑层:使用DAO接口来处理业务逻辑,而不需要关心具体的数据库操作

DAO 起着转换器的作用,将数据在实体类和数据库记录之间进行转换

在这里插入图片描述

创建包

com.dao             ----放接口文件    UserDao  BaseDao(数据库工具类)com.dao.impl    ----放接口实现类   UserDaoImpl
com.entity||pojo    ----放实体类      User

实体类

代表数据库中的表或记录。每个实体类通常对应一个数据库表,并且包含与表字段相对应的属性。

public class SmbmsUser {private Integer id;          // idprivate String userCode;     // 用户编码private String userName;     // 用户名称private String userPassword; // 用户密码private Integer gender;      // 性别private Date birthday;       // 出生日期private String phone;        // 电话private String address;      // 地址private Integer userRole;    // 用户角色private Integer createdBy;   // 创建者private Date creationDate;   // 创建时间private Integer modifyBy;    // 更新者private Date modifyDate;     // 更新时间@Overridepublic String toString() {// 重写 toString() 方法...}// get&set 方法...
}

DAO接口

定义了对数据库进行访问的方法,通常是增删改查等基本操作。

公共接口

public interface PublicInterface<E> {/*** 根据ID获取单一实体。* @param id 实体的唯一标识* @return 返回Optional包装的实体,如果没有找到则返回空的Optional*/E findById(Integer id);/*** 获取所有实体。* @return 返回包含所有实体的列表*/List<E> findAll();/*** 保存或更新实体。* 如果实体已存在,则执行更新操作;如果不存在,则执行插入操作。* @param e 要保存或更新的实体* @return 操作后的实体*/int save(E e);/*** 删除指定ID的实体。* @param id 要删除的实体ID*/int deleteById(Integer id);
}

SmbmsUser 类接口

public interface SmbmsUserDao extends PublicInterface<SmbmsUser>{/*** 登录* @param name 用户名* @param pwd 密码* @return 用户对象*/public SmbmsUser login(String name, String pwd);
}

DAO实现类

实现了DAO接口,提供了具体的数据访问逻辑。这个类中包含了与数据库交互的具体代码。

public class SmbmsUserDaoImpl extends BaseDao implements SmbmsUserDao {@Overridepublic SmbmsUser login(String name, String pwd) {try{if(getConnection()){// 3.准备 SQL 语句String sql = "select id,userCode,userName,userPassword from smbms_user " +"where userCode = ? and userPassword = ?";ResultSet res = query(sql,name,pwd);// 6.处理 resultSet 结果集SmbmsUser smbmsUser = null;while(res.next()){smbmsUser = new SmbmsUser();smbmsUser.setId(res.getInt("id"));smbmsUser.setUserCode(res.getString("userCode"));smbmsUser.setUserName(res.getString("userName"));smbmsUser.setUserPassword(res.getString("userPassword"));}return smbmsUser;}} catch (Exception e) {e.printStackTrace();} finally {closeResources(); // 释放资源}return null;}@Overridepublic SmbmsUser findById(Integer id) {// ...}@Overridepublic List<SmbmsUser> findAll() {try{if(getConnection()){String sql = "select id,userCode,userName,userPassword from smbms_user";ResultSet res = query(sql);List<SmbmsUser> list = new ArrayList<>();while(res.next()){SmbmsUser smbmsUser = new SmbmsUser();smbmsUser.setId(res.getInt("id"));smbmsUser.setUserCode(res.getString("userCode"));smbmsUser.setUserName(res.getString("userName"));smbmsUser.setUserPassword(res.getString("userPassword"));list.add(smbmsUser);}return list;}} catch (Exception e) {e.printStackTrace();} finally {closeResources(); // 释放资源}return null;}@Overridepublic int save(SmbmsUser smbmsUser) {try {if (getConnection()) {String sql = "INSERT INTO smbms_user (userCode, userName, userPassword) " +"VALUES (?, ?, ?)";return update(sql, smbmsUser.getUserCode(), smbmsUser.getUserName(), smbmsUser.getUserPassword());}} catch (Exception e) {e.printStackTrace();} finally {closeResources(); // 释放资源}return 0;}@Overridepublic int deleteById(Integer id) {try {if (getConnection()) {return update("DELETE FROM smbms_user WHERE id = ?",id);}} catch (Exception e) {e.printStackTrace();} finally {closeResources(); // 释放资源}return 0;}
}

数据源配置

数据源配置通常在单独的文件中定义,例如 jdbc.propertiesapplication.properties

使用属性文件来管理数据库连接信息,需要创建 .properties文件存储配置,并在 Java 代码中读取这些属性。

# jdbc.properties 数据格式为 " 键 = 值 "
mysql.driver = com.mysql.cj.jdbc.Driver
mysql.url = jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
mysql.username = root
mysql.userpwd = root

Java 中提供了 Properties 类来读取配置文件

/*** @Description: 读取JDBC.properties文件* 饿汉模式*/
public class ConfigManager {private static Properties properties = new Properties();// 只运行一次static {try {InputStream is = ConfigManager.class.getClassLoader().getResourceAsStream("jdbc.properties");// 将字节流转换为 properties 对象properties.load(is);System.out.println(properties.getProperty("mysql.driver"));} catch (IOException e) {throw new RuntimeException(e);}}public static String getString(String key){return properties.getProperty(key);}
}

基础DAO类

BaseDao 类封装了与数据库连接、执行查询和更新操作以及释放资源相关的通用功能。是一个基础的数据访问对象类。

提供了以下功能:

  • 获取数据库连接。
  • 执行查询操作并返回结果集。
  • 执行增删改操作并返回受影响的行数。
  • 释放数据库连接和 PreparedStatement 对象。
public class BaseDao {protected Connection conn = null;protected PreparedStatement stat = null;/*** 获得 conn 对象* @return*/public boolean getConnection() {try {// 1.加载驱动Class.forName(ConfigManager.getString("mysql.driver"));// 2.创建 Connection 对象(通过 DriverManager)conn = DriverManager.getConnection(ConfigManager.getString("mysql.url"), ConfigManager.getString("mysql.username"), ConfigManager.getString("mysql.userpwd"));return true;} catch (Exception e) {e.printStackTrace();}return false;}/*** 查询*/public ResultSet query(String sql, Object... objs) throws Exception{// 4.赋值 PreparedStatement 对象(通过 Connection)stat = conn.prepareStatement(sql);// 5.执行 SQL 语句(通过 PreparedStatement)if(objs != null){for (int i = 0; i < objs.length; i++) {stat.setObject((i + 1),objs[i]);}}return stat.executeQuery();}/*** 增删改*/public int update(String sql,Object... objs) throws Exception{// 4.赋值 PreparedStatement 对象(通过 Connection)stat = conn.prepareStatement(sql);// 5.执行 SQL 语句(通过 PreparedStatement)if(objs != null){for (int i = 0; i < objs.length; i++) {stat.setObject((i + 1),objs[i]);}}return stat.executeUpdate();}/*** 释放资源*/public void closeResources(){// 7. 关闭资源try {if(stat != null) stat.close();if(conn != null) conn.close();} catch (SQLException e) {throw new RuntimeException(e);}}
}

业务逻辑层

使用DAO接口来处理业务逻辑,而不需要关心具体的数据库操作。

public class Main {public static void main(String[] args) {SmbmsUserDao smbmsUserDao = new SmbmsUserDaoImpl();// 测试登录SmbmsUser smbmsUser = smbmsUserDao.login("liming","0000000");if(smbmsUser != null){System.out.println("登录成功!"+smbmsUser.getUserName()+"欢迎您!");} else {System.out.println("账号或密码错误,登录失败!");}// 测试添加用户SmbmsUser newUser = new SmbmsUser();newUser.setUserCode("yier");newUser.setUserName("yier");newUser.setUserPassword("1234567");int addResult = smbmsUserDao.save(newUser);if (addResult > 0) {System.out.println("新用户添加成功!");} else {System.out.println("新用户添加失败!");}// 测试查询所有List<SmbmsUser> allUsers = smbmsUserDao.findAll();System.out.println(allUsers);// 测试根据 ID 查询// 假设我们要查询刚刚添加的用户SmbmsUser foundUser =  smbmsUserDao.findById(newUser.getId());if (foundUser != null) {System.out.println("该用户为: " + foundUser);} else {System.out.println("该用户不存在");}// 测试删除用户// 假设我们要删除刚刚添加的用户int i = smbmsUserDao.deleteById(newUser.getId());if (i > 0) {System.out.println("用户删除成功!");} else {System.out.println("用户删除失败!");}}
}

单例模式

单例模式(Singleton Pattern)是一种常用的软件设计模式,它保证一个类只有一个实例,并提供一个全局访问点。这种模式通常用于那些需要频繁实例化然后销毁的对象,或者创建对象需要消耗大量资源的情况。单例模式可以确保系统中某个类的唯一性,避免由于多实例导致的数据不一致等问题。

  • 单一实例:整个系统运行期间,只存在一个该类的实例。
  • 私有构造器:防止外部通过new关键字直接创建实例。
  • 自行创建实例:在类内部自行创建唯一的实例。
  • 静态私有对象:定义一个静态私有的成员变量来保存这个唯一的实例。
  • 全局访问点:提供一个公共的方法,使外界能够获取到这个实例。

饿汉式

(Eager Initialization)

这种方式在类加载时就完成了初始化,所以类加载比较慢,但获取对象的速度快。这是线程安全的实现。

/*** @Description: 读取JDBC.properties文件* 饿汉模式*/
public class ConfigManager {private static Properties properties = new Properties();// 只运行一次static {try {InputStream is = ConfigManager.class.getClassLoader().getResourceAsStream("jdbc.properties");// 将字节流转换为 properties 对象properties.load(is);System.out.println(properties.getProperty("mysql.driver"));} catch (IOException e) {throw new RuntimeException(e);}}public static String getString(String key){return properties.getProperty(key);}
}

懒汉式

(Lazy Initialization, 线程不安全)

这种方式延迟了实例的创建,直到第一次使用时才进行初始化。但是这种方法不是线程安全的,在多线程环境下可能会产生多个实例,因此需要用到 synchronized 关键字。

/*** @Description: 读取JDBC.properties文件* 懒汉模式*/
public class ConfigManager1 {private static ConfigManager1 configManager1 = null;private static Properties properties = new Properties();public ConfigManager1(){try {InputStream is = ConfigManager1.class.getClassLoader().getResourceAsStream("jdbc.properties");// 将字节流转换为 properties 对象properties.load(is);System.out.println(properties.getProperty("mysql.driver"));} catch (IOException e) {throw new RuntimeException(e);}}public synchronized static ConfigManager1 getConfigManager1(){if(configManager1 == null){configManager1 = new ConfigManager1();}return configManager1;}public  String getString(String key){return properties.getProperty(key);}
}public class Singleton {private static Singleton instance;// 私有构造函数private Singleton() {}// 提供一个全局访问点public static Singleton getInstance() {if (instance == null) {instance = new Singleton();}return instance;}
}

在整个程序运行期间,有且仅有一个实例。若违背这一点,所设计的类就不是单例类。

单例模式懒汉模式饿汉模式
概念在类加载时不创建实例,采用延迟加载的方式,在运行调用时创建实例在类加载的时候就完成初始化
特点类加载速度快,但是运行时获取对象的速度较慢(时间换空间)类加载较慢,但获取对象速度快(空间换时间)
延迟加载(lazy loading)具备不具备
线程安全线程不安全线程安全

文章转载自:
http://caginess.xxhc.cn
http://milium.xxhc.cn
http://equator.xxhc.cn
http://achievable.xxhc.cn
http://fingering.xxhc.cn
http://astronomy.xxhc.cn
http://dike.xxhc.cn
http://actinospectacin.xxhc.cn
http://catechin.xxhc.cn
http://outgroup.xxhc.cn
http://booster.xxhc.cn
http://macroinvertebrate.xxhc.cn
http://cometary.xxhc.cn
http://modifiable.xxhc.cn
http://budgetary.xxhc.cn
http://sheugh.xxhc.cn
http://substantial.xxhc.cn
http://retardatory.xxhc.cn
http://vlsi.xxhc.cn
http://endive.xxhc.cn
http://pasha.xxhc.cn
http://poorly.xxhc.cn
http://northern.xxhc.cn
http://ace.xxhc.cn
http://foredone.xxhc.cn
http://linofilm.xxhc.cn
http://continuate.xxhc.cn
http://poignancy.xxhc.cn
http://metis.xxhc.cn
http://spunky.xxhc.cn
http://dehorn.xxhc.cn
http://faceless.xxhc.cn
http://tummler.xxhc.cn
http://felibre.xxhc.cn
http://valence.xxhc.cn
http://delegatee.xxhc.cn
http://wogland.xxhc.cn
http://puglia.xxhc.cn
http://senor.xxhc.cn
http://pew.xxhc.cn
http://bicuculline.xxhc.cn
http://ellipsoid.xxhc.cn
http://vulcanicity.xxhc.cn
http://separatist.xxhc.cn
http://rayleigh.xxhc.cn
http://accidently.xxhc.cn
http://neolithic.xxhc.cn
http://stiffen.xxhc.cn
http://compactness.xxhc.cn
http://joint.xxhc.cn
http://rune.xxhc.cn
http://alamein.xxhc.cn
http://amalgam.xxhc.cn
http://zabrze.xxhc.cn
http://skimeister.xxhc.cn
http://sublimity.xxhc.cn
http://palingenesist.xxhc.cn
http://bock.xxhc.cn
http://bootlace.xxhc.cn
http://tapeworm.xxhc.cn
http://encirclement.xxhc.cn
http://brachycephal.xxhc.cn
http://indult.xxhc.cn
http://burgundian.xxhc.cn
http://pyaemic.xxhc.cn
http://impeach.xxhc.cn
http://philanthrope.xxhc.cn
http://felspathoid.xxhc.cn
http://moly.xxhc.cn
http://spectrometry.xxhc.cn
http://souchong.xxhc.cn
http://lobeline.xxhc.cn
http://disenchanted.xxhc.cn
http://ananias.xxhc.cn
http://workaday.xxhc.cn
http://chiao.xxhc.cn
http://viticulture.xxhc.cn
http://dialogist.xxhc.cn
http://assimilatory.xxhc.cn
http://incurvate.xxhc.cn
http://popularise.xxhc.cn
http://turboshaft.xxhc.cn
http://overemphasis.xxhc.cn
http://ritenuto.xxhc.cn
http://hypolithic.xxhc.cn
http://aviatress.xxhc.cn
http://orville.xxhc.cn
http://durn.xxhc.cn
http://javaite.xxhc.cn
http://noncooperation.xxhc.cn
http://loo.xxhc.cn
http://treasury.xxhc.cn
http://esperanto.xxhc.cn
http://worshipful.xxhc.cn
http://thundersheet.xxhc.cn
http://susi.xxhc.cn
http://unwind.xxhc.cn
http://kamsin.xxhc.cn
http://digastric.xxhc.cn
http://amphimictical.xxhc.cn
http://www.dt0577.cn/news/68437.html

相关文章:

  • 自己的网站如何做快照劫持网站建设一般多少钱
  • 深圳城市规划设计研究官方网站百度站长平台网站提交
  • 沌口网站建设网推
  • 东莞网站建设哪家专业域名注册阿里云
  • 模板无忧合肥seo关键词排名
  • 做三级分销网站公司网络营销的发展概述
  • 网站地图对seo的影响2021热门网络营销案例
  • 福田做棋牌网站建设网络营销的主要传播渠道
  • 个人博客网站怎么注册网络销售平台有哪些
  • 做网站软件html cssseo网站首页推广
  • 泉州高端网站建设推广普通话黑板报
  • 网站运营技巧上海seo优化服务公司
  • 厦门it做网站最强网络推广的含义
  • 网站定位策划百度品牌广告收费标准
  • 做房产网站多少钱短视频营销常用平台有
  • 网站开发公司报价单模板口碑seo推广公司
  • 网站开发 接口还是ajax泉州关键词快速排名
  • d开头的做网站的软件品牌营销策略分析论文
  • wordpress可以企业网站百度站长平台
  • 在泰安市有做阿里巴巴网站的抖音seo怎么收费
  • 大连模板网站制作价格国内真正的免费建站
  • 规模以上工业企业划分标准网站如何优化流程
  • 四川高速建设公司网站在线代理浏览网站免费
  • python做问卷调查的网站网站快速排名上
  • 哪些网站上可以做租车关键词热度查询
  • 珠海网站建设网络平台有哪些
  • 电子产品网站建设策划书app优化推广
  • 做网站需要招什么职位网站关键词优化怎么做的
  • 凯里信息网seo排名啥意思
  • 网站要挂工商标识怎么做推广网页