Skip to content

Commit

Permalink
hibernate will persist every changes made to entities during the sess…
Browse files Browse the repository at this point in the history
…ion, so in ConfigChangeContentBuilder case, we should clone the entity first to not trigger unnecessary writes to the db
  • Loading branch information
nobodyiam committed Jan 23, 2018
1 parent 13eda7c commit 3fc83f1
Showing 1 changed file with 17 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.BeanUtils;


public class ConfigChangeContentBuilder {
Expand All @@ -22,22 +23,22 @@ public class ConfigChangeContentBuilder {

public ConfigChangeContentBuilder createItem(Item item) {
if (!StringUtils.isEmpty(item.getKey())){
createItems.add(item);
createItems.add(cloneItem(item));
}
return this;
}

public ConfigChangeContentBuilder updateItem(Item oldItem, Item newItem) {
if (!oldItem.getValue().equals(newItem.getValue())){
ItemPair itemPair = new ItemPair(oldItem, newItem);
ItemPair itemPair = new ItemPair(cloneItem(oldItem), cloneItem(newItem));
updateItems.add(itemPair);
}
return this;
}

public ConfigChangeContentBuilder deleteItem(Item item) {
if (!StringUtils.isEmpty(item.getKey())) {
deleteItems.add(item);
deleteItems.add(cloneItem(item));
}
return this;
}
Expand All @@ -48,16 +49,18 @@ public boolean hasContent(){

public String build() {
//因为事务第一段提交并没有更新时间,所以build时统一更新
Date now = new Date();

for (Item item : createItems) {
item.setDataChangeLastModifiedTime(new Date());
item.setDataChangeLastModifiedTime(now);
}

for (ItemPair item : updateItems) {
item.newItem.setDataChangeLastModifiedTime(new Date());
item.newItem.setDataChangeLastModifiedTime(now);
}

for (Item item : deleteItems) {
item.setDataChangeLastModifiedTime(new Date());
item.setDataChangeLastModifiedTime(now);
}
return gson.toJson(this);
}
Expand All @@ -73,4 +76,12 @@ public ItemPair(Item oldItem, Item newItem) {
}
}

Item cloneItem(Item source) {
Item target = new Item();

BeanUtils.copyProperties(source, target);

return target;
}

}

0 comments on commit 3fc83f1

Please sign in to comment.