DAO(Database Access Object
数据库访问对象)
为了降低耦合性,提出了DAO封装数据库操作的设计模式。
它可以实现业务逻辑与数据库访问相分离。相对来说,数据库是比较稳定的,其中DAO组件依赖于数据库系统,提供数据库访问的接口,隔离了不同的数据库实现。
DAO模式的组成部分
1 DAO接口(主要包 添加 修改 查询 删除方法)
2 DAO实现类
3 实体类 (domain、beans、entity、pojo、model)
PO (VO)(Persistent Object, Value Object)
VO (View Object)
DTO (Data Transfer Object)
--作用:用在数据访问代码和业务逻辑代码之间通过实体类来传输数据
--实体类特征:
◦属性一般使用private修饰
◦提供public修饰的getter/setter方法
◦实体类提供无参构造方法,根据业务提供有参构造
◦实现java.io.Serializable接口,支持序列化机制
4 数据库连接和关闭工具类
设计的包名 :
domain 存放实体类
utils 存放工具类
dao 存放接口
dao.impl 存放实现类
使用DAO设计模式实现emp表的查询、添加、删除、修改
图示
utils工具类
代码(使用阿里连接池druid);
public class DataSourceUtils {
private static DruidDataSource dataSource;
static {
try {
Properties properties = new Properties();
InputStream is = DataSourceUtils.class.getClassLoader().getResourceAsStream( "druid.properties" );
properties.load( is );
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource( properties );
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection(){
try {
return dataSource.getConnection( );
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
配置文件:
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mysql?useSSL=true&characterEncoding=utf8
username=root
password=root
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=5000
实体类Emp:
public class