首页JavaBee 正文

update高级用法说明(十三)

时间: 2021年1月8日 浏览 238

文章来源网络,只为推广技术,若有侵权,联系删除文章。

SQL的update分为set 部分和 where部分,一部分是要设置更新的部分,另一部分是条件部分。
语法,如:
update table_name set max_id=max_id+1 where id=1001
要是没有where条件,则会将所有的记录都更新(在生产环境,是极少会用到的)

具体使用分如下几用情况。

1. 字段只出现在set或where部分
set部分(设值部分)的表达式,只能用=.
因Bee可以默认将entity的值转为=等号的表达式,因此只需要批量是set还是where 的部分即可。

Suid接口的update方法:
public int update(T entity);
这个方法用于SQL的where条件的只有id属性,其它非null(且非空字符串)字段将更新到数据库(id除外)

其它update相关的方法在SuidRich接口。
当set的部分较少时,可以指定某些字段是为set部分, 其它则为where部分;
方法名为 update .
当where的部分较少时,可以指定某些字段为where部分,其它则为set部分;
方法名为, updateBy ,即通过条件进行更新。
当然,还可以用IncludeType指定是否要包含null , 空字符。

相关例子: (五): 复杂查询(面向对象方式)

2. 某一字段同时出现在set和where部分
如转账,先要查询某用户的账户余额是否够,然后才能转。

假设要转1000,查出来是1200.
则直接写sql,语句类似:
update set balance=balance-1000 where user='peter' and balance=1200;
balance要同时出现在set和where,也放在where作为条件,可以防止在查询后,更新前的时间,记录被人更改过。

	        entity=new Account();
		entity.setUser("peter");
		entity=suidRich.selectOne(entity);

                //balance>=1000
		
		Condition condition2=new ConditionImpl();
		condition2.setAdd("balance", -1000); 
		int updateNum=suidRich.update(entity,condition2);  //ok

3. 更新的字段是在原来的基础上变化
如某类商品提价2元,可以有如下写法。
set price=price+2
这样写的好处,可以不需要查询出原来的价格,减少IO开销。
Bee的面向对象写法:
condition.setAdd("price", 2);
suidRich.update(entity,condition);

若字段p每次增加的值由字段step配置,则写为:
condition.setAdd("p", "step");
会转化为: set p=p+step

相关例子: (五): 复杂查询(面向对象方式)

4. 复杂where条件
对于where条件中,不能用=等号表达的,通过Condition接口实现。