新增/修改时,唯一性字段检查

一个对象,比如订单Order
有一个无意义的orderId作为唯一标识属性,还有一个有意义的订单号orderNo
orderNo也必须是唯一的,在添加修改数据的时候,就存在校验唯一性的问题

先假设有表order,保含2个字段,orderid,orderNo

1.新增
我们写一个通用的校验类,有一个check方法,参数为表名,校验的列名,列的值


CheckUnique.java


public class CheckUnique {
public static boolean check(
String tablemame,
String coluname,
String coluvalue)
throws BaseException {

boolean isExist = false;

Connection con = null;
Statement pstmt = null;
ResultSet rs = null;

try {
con = BaseDAO.getConnection();
String strSql = "";
strSql =
"select count(1) as count from "
+ tablemame
+ " where "
+ coluname
+ "="
+ coluvalue;

Debug.printErr(strSql);

pstmt = con.createStatement();
rs = pstmt.executeQuery(strSql);
int totalNum = 0;
if (rs.next()) {
totalNum = rs.getInt("count");

if (totalNum != 0)
isExist = true;
}

} catch (SQLException sql) {
try {
if (con != null)
con.rollback();
} catch (Exception e) {
}
throw new BaseException(sql.getMessage());
} finally {
try {
rs.close();
} catch (SQLException e) {
}
try {
pstmt.close();
} catch (SQLException e) {
}
}
return isExist;
}
}

现在我们就可以通过CheckUnique.check("order","orderNo","20050501111")来校验orderNo

2.修改
修改的校验要比新增麻烦,因为修改的时候,检测orderNo当然是存在了。
在CheckUnique类添加新方法checkUpdate(String tableName, //表名
String idColName, //主键列名
String idColValue, //主键列值
String uniColName, //校验列名
String uniColVaue) //校验列值
方法内容基本和check()方法一样,只是sql语句strSql不同,strSql如下

select count(1) as count from tableName t1
where t1.uniColName=uniColVaue
and t1.idColName not in
(
select t2.idColName from tableName t2
where t2.idColName=idColValue and t2.uniColName=uniColVaue
)

order的例子
select count(1) as count from order t1
where t1.orderNo='200505001111'
and t1.orderId not in
(
select t2.orderId from order t2
where t2.orderId=9527 and t2.orderNo='200505001111'
)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值