本系列博客内容为:做DRP系统中Dao层常用功能。

该项目采用MVC架构

  1. C(Controller)控制器,主要职责;1、取得表单参数;2、调用业务逻辑;3、转向页面
  2. M(Model)模型,主要职责:1、业务逻辑;2、保存数据的状态
  3. V(View)视图,主要职责:显示

本文主要是针对于Dao层的常见使用方法:增删改查sql语句及常用操作。

 package com.bjpowernode.drp.basedata.dao;

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import com.bjpowernode.drp.basedata.domain.Item;
import com.bjpowernode.drp.util.ApplicationException;
import com.bjpowernode.drp.util.DbUtil;
import com.bjpowernode.drp.util.PageModel;
import com.bjpowernode.drp.util.datadict.domain.ItemCategory;
import com.bjpowernode.drp.util.datadict.domain.ItemUnit; public class ItemDao4OracleImpl implements ItemDao {
//增加物料信息
public void addItem(Connection conn, Item item) {
String sql = "insert into t_items (item_no, item_name, spec, pattern, item_category_id, item_unit_id) ";
sql+=" values (?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = null;
try {
//Dao的设计粒度一般是细粒度的,如果没有特殊需求,Dao和Manager粒度可以一样,不同考虑太多
//Dao的设计是比较单纯的,不应该放入过多的业务逻辑(业务规则)
//如果放置了业务逻辑,有些Manager不采用此业务逻辑,这样这个Dao方法就没有复用率了
//对于我们的应用来说Dao最底层的,所以应该越通用越好
// if (findItemById(conn, item.getItemNo()) != null) {
// throw new ApplicationException("物料代码已经存在,代码=" + item.getItemNo() + "");
// }
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, item.getItemNo());
pstmt.setString(2, item.getItemName());
pstmt.setString(3, item.getSpec());
pstmt.setString(4, item.getPattern());
pstmt.setString(5, item.getItemCategory().getId());
pstmt.setString(6, item.getItemUnit().getId());
pstmt.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
//System.out.println("errorCode=" + e.getErrorCode());
//System.out.println("description=" + e.getMessage());
// if (e.getErrorCode() == 1) {
// throw new ApplicationException("物料代码已经存在,代码【" + item.getItemNo() + "】");
// }
throw new ApplicationException("添加物料失败!");
}finally {
DbUtil.close(pstmt);
}
}
//删除物料信息数组
public void delItem(Connection conn, String[] itemNos) {
StringBuffer sbString = new StringBuffer();
for (int i=0; i<itemNos.length; i++) {
sbString.append("?");
if (i < (itemNos.length - 1)) {
sbString.append(",");
}
}
String sql = "delete from t_items where item_no in(" + sbString.toString() + ")";
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
for (int i=0; i<itemNos.length; i++) {
pstmt.setString(i+1, itemNos[i]);
}
pstmt.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
throw new ApplicationException("删除物料失败!");
}finally {
DbUtil.close(pstmt);
}
}
//通过Id查询物料信息
public Item findItemById(Connection conn, String itemNo) {
StringBuffer sbSql = new StringBuffer();
//第一中方法
sbSql.append("select a.item_no, a.item_name, a.spec, a.pattern, a.item_category_id, ")
.append("b.name as item_category_name, a.item_unit_id, c.name as item_unit_name ")
.append("from t_items a, t_data_dict b, t_data_dict c ")
.append("where a.item_category_id=b.id and a.item_unit_id=c.id and a.item_no=?"); // //第二中方法
// sbSql.append("select a.item_no, a.item_name, a.spec, a.pattern, a.category as category_id, ")
// .append("(select b.name from t_data_dict b where a.category=b.id) as category_name, ")
// .append("a.unit as unit_id, ")
// .append("(select c.name from t_data_dict c where a.unit=c.id) as unit_name ")
// .append("from t_items a where a.item_no=?"); //通常采用日志组件记录,如log4j, 级别:info,debug,error... PreparedStatement pstmt = null;
ResultSet rs = null;
Item item = null;
try {
pstmt = conn.prepareStatement(sbSql.toString());
pstmt.setString(1, itemNo);
rs = pstmt.executeQuery();
if (rs.next()) {
item = new Item();
item.setItemNo(rs.getString("item_no"));
item.setItemName(rs.getString("item_name"));
item.setSpec(rs.getString("spec"));
item.setPattern(rs.getString("pattern"));
//构造ItemCategory
ItemCategory ic = new ItemCategory();
ic.setId(rs.getString("item_category_id"));
ic.setName(rs.getString("item_category_name"));
item.setItemCategory(ic); //构造ItemUnit
ItemUnit iu = new ItemUnit();
iu.setId(rs.getString("item_unit_id"));
iu.setName(rs.getString("item_unit_name"));
item.setItemUnit(iu);
}
}catch(SQLException e) {
e.printStackTrace();
//记录到日志文件 error
throw new ApplicationException("根据物料代码查询出错,物料代码[" + itemNo + "]");
}finally {
DbUtil.close(rs);
DbUtil.close(pstmt);
}
return item;
}
//根据pageNO、pageSize、condation显示很多物料信息列表
public PageModel findItemList(Connection conn, int pageNo, int pageSize, String condation) {
StringBuffer sbSql = new StringBuffer(); //第一中方法
// sbSql.append("select a.item_no, a.item_name, a.spec, a.pattern, a.item_category_id, ")
// .append("b.name as item_category_name, a.item_unit_id, c.name as item_unit_name ")
// .append("from t_items a, t_data_dict b, t_data_dict c ")
// .append("where a.item_category_id=b.id and a.item_unit_id=c.id and a.item_no=?"); // //第二中方法
// sbSql.append("select a.item_no, a.item_name, a.spec, a.pattern, a.category as category_id, ")
// .append("(select b.name from t_data_dict b where a.category=b.id) as category_name, ")
// .append("a.unit as unit_id, ")
// .append("(select c.name from t_data_dict c where a.unit=c.id) as unit_name ")
// .append("from t_items a where a.item_no=?"); sbSql.append("select * ")
.append("from (")
.append("select i.*, rownum rn from (")
.append("select a.item_no, a.item_name, a.spec, a.pattern, a.item_category_id, ")
.append("b.name as item_category_name, a.item_unit_id, c.name as item_unit_name ")
.append("from t_items a, t_data_dict b, t_data_dict c ")
.append("where a.item_category_id=b.id and a.item_unit_id=c.id ");
if (condation != null && !"".equals(condation)) {
sbSql.append(" and (a.item_no like '" + condation + "%' or a.item_name like '" + condation + "%') ");
}
sbSql.append(" order by a.item_no")
.append(") i where rownum<=? ")
.append(") ")
.append("where rn >? ");
System.out.println("sql=" + sbSql.toString()); //通常采用日志组件记录,如log4j, 级别:info,debug,error...
PreparedStatement pstmt = null;
ResultSet rs = null;
PageModel pageModel = null;
try {
pstmt = conn.prepareStatement(sbSql.toString());
pstmt.setInt(1, pageNo * pageSize);
pstmt.setInt(2, (pageNo - 1) * pageSize);
rs = pstmt.executeQuery();
List itemList = new ArrayList();
while (rs.next()) {
Item item = new Item();
item.setItemNo(rs.getString("item_no"));
item.setItemName(rs.getString("item_name"));
item.setSpec(rs.getString("spec"));
item.setPattern(rs.getString("pattern"));
//构造ItemCategory
ItemCategory ic = new ItemCategory();
ic.setId(rs.getString("item_category_id"));
ic.setName(rs.getString("item_category_name"));
item.setItemCategory(ic); //构造ItemUnit
ItemUnit iu = new ItemUnit();
iu.setId(rs.getString("item_unit_id"));
iu.setName(rs.getString("item_unit_name"));
item.setItemUnit(iu); itemList.add(item);
}
pageModel = new PageModel();
pageModel.setPageNo(pageNo);
pageModel.setPageSize(pageSize);
pageModel.setList(itemList);
//根据条件取得记录数
int totalRecords = getTotalRecords(conn, condation);
pageModel.setTotalRecords(totalRecords);
}catch(SQLException e) {
e.printStackTrace();
//记录到日志文件 error
throw new ApplicationException("分页查询失败");
}finally {
DbUtil.close(rs);
DbUtil.close(pstmt);
}
return pageModel;
} /**
* 根据条件取得记录数
* @param conn
* @param queryStr
* @return
*/
private int getTotalRecords(Connection conn, String condation)
throws SQLException {
String sql = "select count(*) from t_items ";
if (condation != null && !"".equals(condation)) {
sql+="where item_no like '" + condation + "%' or item_name like '" + condation + "%' ";
}
PreparedStatement pstmt = null;
ResultSet rs = null;
int temp = 0;
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
rs.next();
temp = rs.getInt(1);
}finally {
DbUtil.close(rs);
DbUtil.close(pstmt);
}
return temp;
}
//修改物料信息
public void modifyItem(Connection conn, Item item) {
String sql = "update t_items set item_name=?, spec=?, pattern=?, item_category_id=?, item_unit_id=? ";
sql+=" where item_no=?";
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, item.getItemName());
pstmt.setString(2, item.getSpec());
pstmt.setString(3, item.getPattern());
pstmt.setString(4, item.getItemCategory().getId());
pstmt.setString(5, item.getItemUnit().getId());
pstmt.setString(6, item.getItemNo());
pstmt.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
throw new ApplicationException("修改物料失败!");
}finally {
DbUtil.close(pstmt);
}
} }

【DRP】-Dao层常用功能代码:增删改查的更多相关文章

  1. DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)

    DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类) 一.DAO模式简介 DAO即Data Access Object,数据访问接口.数据访问:故名思义就是与数据库打交道.夹在业务逻辑与数据 ...

  2. zkCli的使用 常用的节点增删改查命令用法

    zkCli的使用 常用的节点增删改查命令用法 1. 建立会话  命令格式:zkCli.sh -timeout 0 -r -server ip:port ./zkCli.sh -server -time ...

  3. MYSQL的常用命令和增删改查语句和数据类型

    连接命令:<a href="http://lib.csdn.net/base/mysql" class='replace_word' title="MySQL知识库 ...

  4. MYSQL的常用命令和增删改查语句和数据类型【转】

    连接命令:<a href="http://lib.csdn.net/base/mysql" class='replace_word' title="MySQL知识库 ...

  5. .NET Core实战项目之CMS 第十五章 各层联动工作实现增删改查业务

    连着两天更新叙述性的文章大家可别以为我转行了!哈哈!今天就继续讲讲我们的.NET Core实战项目之CMS系统的教程吧!这个系列教程拖得太久了,所以今天我就以菜单部分的增删改查为例来讲述下我的项目分层 ...

  6. SQL学习之MYSQL的常用命令和增删改查语句和数据类型

    连接命令:mysql -h[主机地址] -u[用户名] -p[用户密码] 创建数据库:create database [库名] 显示所有数据库: show databases; 打开数据库:use [ ...

  7. MySQL数据库学习笔记(十一)----DAO设计模式实现数据库的增删改查(进一步封装JDBC工具类)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  8. JS源生代码“增删改查”之增

    51呢最近在做一个管理数据的,第一次接触到用JS的源代码去实现一些功能,才知道网页里的许多功能都是依赖于“增删改查”完成的,下面的几张图片就是对于增的演示: 下面是有关HTML的代码:这个主要是弹窗部 ...

  9. HBase入门操作 常用命令和增删改查的简单应用操作

    这里启动关闭Hadoop和HBase的顺序一定是: 启动Hadoop—>启动HBase—>关闭HBase—>关闭Hadoop ssh localhost 开启hadoopcd /us ...

随机推荐

  1. SQLite的查询优化

    SQLite是个典型的嵌入式DBMS,它有很多优点,它是轻量级的,在编译之后很小,其中一个原因就是在查询优化方面比较简单,它只是运用索引机制来进行优化的,经过对SQLite的查询优化的分析以及对源代码 ...

  2. android 流量统计

    1 android通过架构流量统计TrafficStats类可以直接获得     获得总流量受理TrafficStats.getTotalRxBytes(),     获得总传出流量TrafficSt ...

  3. C# 程序内的类数量对程序启动的影响

    原文:C# 程序内的类数量对程序启动的影响 版权声明:博客已迁移到 http://lindexi.gitee.io 欢迎访问.如果当前博客图片看不到,请到 http://lindexi.gitee.i ...

  4. numpy 下的数据结构与数据类型的转换(np.array vs. np.asarray)

    1. np.asarray -- numpy 风格的类型转换 从已有多维数组创建新的多维数组,数据类型可重新设置 >> B = np.asarray(A, dtype='int32') 2 ...

  5. Attribute-based identification schemes for objects in internet of things

    Methods and arrangements for object identification. An identification request is received from diffe ...

  6. sgu209:Areas(计算几何)

    意甲冠军: 给一些直.这架飞机被分成了很多这些线性块.每个块的需求面积封闭曲线图. 分析: ①我们应要求交点22的直线: ②每行上的交点的重排序,借此来离散一整行(正反两条边): ③对于连向一个点的几 ...

  7. Customize Acrylic Brush in UWP Applications(在UWP中自定义亚克力笔刷)

    原文 Customize Acrylic Brush in UWP Applications(在UWP中自定义亚克力笔刷) Windows 10 Fall Creators Update(Build ...

  8. 工作流管理平台Airflow

    Airflow 1. 引言 Airflow是Airbnb开源的一个用Python写就的工作流管理平台(workflow management platform).在前一篇文章中,介绍了如何用Cront ...

  9. Windows下安装MySQL(解压版本)

    解压缩 将下载到的文件解压缩到自己喜欢的位置,例如我自己的位置是D:\Program Files\mysql-5.7.10-winx64 添加环境变量 右键计算机->属性->高级系统设置- ...

  10. hdu3118Arbiter (使用二分图的定义,枚举每个状态)

    Arbiter Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) Total Sub ...