Hibernate避免不必要的更新语句

时间:2016-02-03 09:04:27

标签: java oracle hibernate

我知道Oracle将空字符串视为空值。因此,如果我使用新值执行批处理作业来更新实体,那么 Hibernate / Oracle 将执行更新语句,例如,如果我将空字符串值设置为属性值。但是,如果我间接地像这个方法 updateStringContainerIndirect 那样做,那么没有任何反应。为什么会这样?

说我有以下实体:

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class StringContainer {

    @Id
    private int id;

    private String stringValue;

    @Version
    private int entityVersion;

    //Getter Setter...
}

这是我的TestClass:

public class StringTest {

    private static Repository repository;
    private List<StringContainer> stringContainerValues;

    @Before
    public void loadData() {
        stringContainerValues = repository.getStringContainers();
        for (StringContainer stringContainer : stringContainerValues) {
            stringContainer.setStringValue("");
        }
    }

    @After
    public void clearData() {
        stringContainerValues = null;
    }

    @Test
    public void updateStringContainerDirectIncrementVersionNumber() {
        for (StringContainer stringContainer : stringContainerValues) {
            long oldEntityVersion = stringContainer.getEntityVersion();
            updateStringContainerDirect(stringContainer, "");
            Assert.assertEquals(oldEntityVersion++, stringContainer.getEntityVersion());
        }
    }

    @Test
    public void updateStringContainerNoIncrementVersionNumber() {
        for (StringContainer stringContainer : stringContainerValues) {
            long oldEntityVersion = stringContainer.getEntityVersion();
            updateStringContainerIndirect(stringContainer, "");
            Assert.assertEquals(oldEntityVersion, stringContainer.getEntityVersion());
        }
    }

    public void updateStringContainerDirect(StringContainer stringContainer, String newValue) {
        stringContainer.setStringValue(newValue);
    }

    public void updateStringContainerIndirect(StringContainer stringContainer, String newValue) {
        String dbString = stringContainer.getStringValue();
        dbString = newValue;
        stringContainer.setStringValue(dbString);
    }
}

0 个答案:

没有答案